So I am playing with React and Redux for the first time. In my app, I am using a third party API to fetch data and so on, all is well in that regard. However like most protected APIs I need to fetch a short lived token to make requests against the API, I want to set a timer on some sort of event so that I can refresh my token in the background. What is the best way to do this? The token comes with an expiry so I can set a timer to fetch a new token a few minutes prior to the tokens expiry.
相关问题
- How to toggle on Order in ReactJS
- Refreshing page gives Cannot GET /page_url in reac
- Adding a timeout to a render function in ReactJS
- React Native Inline style for multiple Text in sin
- Issue with React.PropTypes.func.isRequired
相关文章
- Cannot find module 'redux' 怎么解决?
- Why would we use useEffect without a dependency ar
- Is it possible to get ref of props.children?
- Stateless function components cannot be given refs
- React testing library: Test attribute / prop
- React/JestJS/Enzyme: How to test for ref function?
- Material-UI [v0.x] RaisedButton on hover styles
- Remove expo from react native
First solution I came up with is to nest the promises, but it might not be the best solution.
First request your token and in
then
callback request the real data.With
axios
it would be something like this:Add catches to this requests. If token has expiry date as you said, you can save it and create some kind of condition to check if that date didn't expired and request new token or take existing based on that condition.
Example in pseudo code:
What you can do is save the token you get as a cookie with a expiration period and then set timer to monitor the cookie using the
setInterval
function. The cookie automatically gets removed from the browser as soon as its expiration period gets over and it returns undefined, so then you can make a API call againYou can use the npm package
react-cookie
for this purposeTimer
SetCookie
You could go the stateless route and always query the API with whatever token you have and handle the unauthorised response?
You will need to handle an unauthorised response at some point so this would solve both cases.
Perhaps wrapping your
axios
calls would enable this?