Dispatch action after some elapsed period

2019-05-26 13:48发布

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.

3条回答
唯我独甜
2楼-- · 2019-05-26 14:23

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:

axios.get('/my/token/path/')
.then(() => {
    axios.get('/my/real/data/path')
    .then(() => {
         // do something with data...
    }
}

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:

function getTokenPromise() {
    if ('cookie with token exists') return Promise.resolve('my token from cookie');

    return axios.get('/my/token/path/');
}

// somewhere else in the code

getTokenPromise().then(() => {
    //do something with data
});
查看更多
smile是对你的礼貌
3楼-- · 2019-05-26 14:27

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 again

You can use the npm package react-cookie for this purpose

import cookie from 'react-cookie';

Timer

setInterval(function() {
   var  getCookie = cookie.load('token');

   if(getCookie === undefined) {
      // send an API fetch request here
  } 
}, 10000);

SetCookie

var s = new Date(0); 
 s.setUTCSeconds(exp);
 cookie.save(key,value, {expires: s});
查看更多
孤傲高冷的网名
4楼-- · 2019-05-26 14:30

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?

查看更多
登录 后发表回答