I'm using react js with fetch ,I wanna call an api of refresh token Before my token be expired ,then I calculate the difference between my local date and expire date of the token . I want to call my refresh token api every (expire - localData) - 5 min and update my token in my localStorage. Is that possible ? A call my refresh token in Api.js to work globally ,Is that right ? This is my code but doesn't work like excepting:
Api.js
const duration = localStorage.getItem("duration")
useEffect(() =>{
if(token)
setInterval(() => {
RefreshApi.getRefreshToken().then(res => {
if (typeof res === "string") {
console.log("Error",res)
} else {
var now = moment(new Date(), "DD/MM/YYYY HH:mm:ss");
var expire = moment(new Date(res.expire), "DD/MM/YYYY HH:mm:ss");
var diffTime = moment.duration(expire.diff(now));
localStorage.setItem("token",res.token);
localStorage.setItem("expireDuration",diffTime.asMilliseconds());
localStorage.setItem("expire",res.expire);
}
}).catch(err => {
console.log(err);
})
},(duration - 300000))
},[])
refreshApi.js
getRefreshToken: function () {
return api.get("/refreshToken",{"Authorization": `Bearer ${localStorage.getItem("token")}`}).then(res => {
if (res.ok) {
return res.json();
} else {
return res.text();
}
});
},
Any help please ?