rt2zz / redux-persist

persist and rehydrate a redux store
MIT License
12.91k stars 862 forks source link

Problem with purging persistor in 1 place but not another. #1414

Closed RobinXia99 closed 9 months ago

RobinXia99 commented 1 year ago

Im trying to call persistor.purge() in my axios interceptor when my refresh token has expired, the idea is that I should log out. This is used on my log out button as well and it works there. But it rarely(only sometimes) purges through my interceptor function (I made sure to log before and after and the logs came through).

The onPress looks like this:

          onPress={async () => {
            await AsyncStorage.clear()
            await persistor.purge()
          }}

The interceptor looks like this:

apiInstance.interceptors.response.use(
  (response) => {
    return response
  },
  async (error) => {
    const originalRequest = error.config

    if (error.response.status === 401 && error.response.config.url === `api/token/refresh/`) {
      await persistor.purge()
      await AsyncStorage.clear()
      return Promise.reject(error)
    }

    if (error.response.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true
      const refresh_token = await AsyncStorage.getItem('refresh')
      const response = await apiInstance.post<{ access: string }>(`api/token/refresh/`, {
        refresh: refresh_token,
      })
      const { access } = response.data
      setAccessToken(access)

      return apiInstance(originalRequest)
    }
    return Promise.reject(error)
  }
)

What confuses me is that sometimes it works, sometimes it doesnt and sometimes I have to hot reload for the purge to call. My guess is that the callbacks/promises are queued somehow or is called at the same time as an api request and just stops working. I have no idea... :( Ive tried purging, flushing and pausing after eachother and theres no difference

arochedy commented 1 year ago

Maybe you can do a clean action in your reducers (I'm doing this when user logout)

in your reducer : case LOGOUT: { return initialState; }