Reputation: 3783
I am having a redux-saga
middleware to facilitate async store operations and all the API calls are made through sagas. Now implementing OAuth2
, I want check if my token is expired then refresh it with refresh token before API call happens. The problem is I am not able to find a solution to intercept the saga to do it. My expiresAt
value is in store state which should be used to make decision whether the access token is expired.
What I want to build
An interceptor that would run before each saga and allows to access redux state and also to trigger redux actions. So that I can access expiresAt
from store to compare it with current datetime and then if token is expired, trigger refresh api to refresh it and subsequently dispatch store actions and then the real saga can work with updated token.
Approaches found till now:
Any help is appreciated. Also, if I am not thinking in right direction with the problem at hand, please let me know about the right way to do it. May be without saga.
Upvotes: 2
Views: 821
Reputation: 11848
I may suggest to use separate generator function which will refresh token in background. The process will look like:
login
. It will dispatch LOGIN_SUCCESS
action to store token in Redux.refreshToken
will listen for LOGIN_SUCCESS
actions and start timer. When timer expires, it will either refresh token or dispatch action for saga that will do token refresh. LOGIN_SUCCESS
will be dispatched that will bring us to step 2.As a result, token will always be refreshed and a user will not experience delay when performing operations.
As additional check you may implement private routes to automatically logoff user in case token refresh failure.
Upvotes: 2