Reputation: 485
So, here I'm making a request to obtain an api token which I use it in the login function after that. That token expires in one hour which make the website stop working. What I want is to obtain a new token automatically after one hour when it expires to handle the expiry of the old token, and also to override the token saved in the session storage. btw I'm not using Redux here.
componentDidMount(){
let url1 = ``;
fetch(url1,{
method: 'POST'
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({authToken: responseJson.auth_token}, ()=>{
sessionStorage.setItem('auth-token', this.state.authToken);
})
})
.catch((error) => {
console.log(error)
});
}
Upvotes: 1
Views: 951
Reputation: 2646
Take a look at below code where fetch the userToken after every 59mins assuming you said token expiry is 1hr in your question. What we do is make the call to fetchToken as soon as the component mounts and start a timer which will repeat this call after 59 mins. Once the component unmounts we clean up and clear the timer. (Note: 59 min is just an assumption, you can fetch the token anytime before expiry)
componentDidMount(){
let url1 = ``;
this.fetchToken();
this.refetchTokenId = setInterval(this.fetchToken, 59 * 60 * 1000)
}
componentWillUnmount() {
clearInterval(this.refetchTokenId)
}
fetchToken = () => {
fetch(url1,{
method: 'POST'
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({authToken: responseJson.auth_token}, ()=>{
sessionStorage.setItem('auth-token', this.state.authToken);
})
})
.catch((error) => {
console.log(error)
});
}
Upvotes: 1