0
votes

I recently ran into an issue with React Native and Redux while implementing OAuth which provoked some amount of head-scratching. The scenario is as follows:

  • I use Redux in my React Native app
  • The user logs in and the refresh token and access token are stored.
  • In an action creator for another component the user needs to call a rest endpoint with the short-lived access token.
  • However, for every call, the user needs to call a service method like getAccessToken() which will always return a valid access token, and if the tokens are expiring it will renew them and will update the store.

The data flow in Redux is strictly unidirectional, meaning, the user calls the action creator, which in turn will call the reducer, which will change the state in the store and the component will re-render with the new state. However, I cannot possiblly bind the state of my component to the access token; every time the user wants to make a Rest call she should call getAccessToken() to make sure that she receives a valid token before sending.

Any suggestions as to how to implement this using React Native and Redux? Thank you.

1

1 Answers

0
votes

How to do it in your way:

  1. Call getAccessToken().then(token => myOtherCall(token))
  2. After the second call succeeds dispatch two actions, one to the corresponding reducer with the result and another one saving the new token.

How I would do it:

Using redux-saga, I would setup a loop that refreshes the token every X seconds. If a request fails because of 401 status code, I would refresh the token and retry the api call.