[英]Trying to call the token API after token expires using ReactJs
I want to call the tokenApiCall as soon as the current time exceeds the expiry time of token in the prior call.我想在当前时间超过先前调用中令牌的到期时间时立即调用 tokenApiCall。 I am caching the token and expiry values in session storage and below is the sample code I have written for the same.
我正在会话存储中缓存令牌和到期值,下面是我为此编写的示例代码。 I am not able to understand how I can make sure it re-renders whenever needed-
我无法理解如何确保它在需要时重新渲染-
import React from 'react';
import axios from 'axios';
class ApiCall extends React.Component {
constructor(props) {
super(props);
this.state = {
token: '',
expiry: ''
};
}
tokenApiCall(){
axios
.post(
'https://api/v1/Getauthtoken',
{
username: 'xyz',
client: 'XYZ',
}
)
.then((res) => {
this.setState({ token: res.token, expiry: res.expires_in});
sessionStorage.setItem('tokenval', this.state.token);
sessionStorage.setItem('tokenExp', this.state.expiry);
})
.catch((error) => {
console.log('Error message is ' + error);
});
}
componentDidMount() {
const curDate = new Date();
let [hour, minutes, seconds] = [curDate.getHours(), curDate.getMinutes(), curDate.getSeconds()];
hour = hour % 12;
hour = hour ? hour : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
const currentTime = hour + ':' + minutes + ':' + seconds;
const exp = sessionStorage.getItem('tokenExp');
if(!sessionStorage.getItem('tokenval')) {
this.tokenApiCall();
}
else {
if(currentTime > exp){
this.tokenApiCall();
}
else
{
console.log("currentTime < exp")
}
}
}
render() {
return <div>Hello</div>
}
}
export default ApiCall;
you can use setTimeout
inside componentDidMount
您可以在
componentDidMount
使用setTimeout
TimeInMilliSeconds
is difference between exp - currentTime
in MilliSeconds. TimeInMilliSeconds
是exp - currentTime
之间的差值, TimeInMilliSeconds
为TimeInMilliSeconds
。
if(currentTime > exp){
this.tokenApiCall();
}
else
{
setTimeout(() => {
this.tokenApiCall();
}, TimeInMilliSeconds)
// TimeInMilliSeconds = exp - currentTime
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.