I have built a blog API that uses tokens (short lived say 60 mins) and refresh tokens (long lived say 1 day). How to make API calls via React-Redux app using a generic function to handle cases of multiple API calls successfully instead of aborting them?
I don’t know redux Saga that much but this would be my approach: assuming that the api calls are wrapped in redux actions and the session timeout is expressed as http error on the request:
Request 1 - error http session invalid or something to read the error - call action method which renews the session token and passes additionally (and optionally) the method to execute after the session has been renewed which is in this case request 1 itself.
This way you can renew the session from every request. I think this should be possible with saga too.
Philip Davis
Software developer
One way to do it would be to have a single saga responsible for making the calls (and doing the refresh-and-retry logic when the token fails)... and you have it take requests from an event channel. On the other side, you can have multiple sagas feeding requests into the event channel.
That is the cleanest method I can think of off the top of my head.
I suppose you could also fork each request and have some kind of synchronization via the store... e.g. once one of the forks gets a token failure, set a "lock" flag in the store to indicate that it is refreshing the token. And then other forks would check for this lock before they attempt to refresh. If the lock is set then they just wait for an action that indicates a new token is ready.
Could make for a good blog post... hmm... :)