经过一段时间后的派遣行动 [英] Dispatch action after some elapsed period
问题描述
所以我第一次使用 React 和 Redux.在我的应用程序中,我使用第三方 API 来获取数据等等,在这方面一切都很好.然而,像大多数受保护的 API 一样,我需要获取一个短期令牌以针对 API 发出请求,我想为某种事件设置一个计时器,以便我可以在后台刷新我的令牌.做这个的最好方式是什么?令牌会过期,因此我可以设置一个计时器,在令牌到期前几分钟获取新令牌.
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.
推荐答案
您可以做的是将您获得的令牌保存为具有有效期的 cookie,然后使用 setInterval设置计时器来监视 cookie代码>功能.cookie 过期后会自动从浏览器中删除并返回 undefined,因此您可以再次调用 API
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
您可以为此使用 npm 包 react-cookie
You can use the npm package react-cookie
for this purpose
import cookie from 'react-cookie';
定时器
setInterval(function() {
var getCookie = cookie.load('token');
if(getCookie === undefined) {
// send an API fetch request here
}
}, 10000);
设置Cookie
var s = new Date(0);
s.setUTCSeconds(exp);
cookie.save(key,value, {expires: s});
这篇关于经过一段时间后的派遣行动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!