New title: Calculate and update a token's remaining expiration time
P粉463840170
2023-08-26 23:13:42
<p>I need to refresh Spotify token every hour in React application (Spotify token is valid for 1 hour). I know the following method uses <strong>useEffect</strong> hook and <strong>setInteral</strong></p>
<pre class="brush:php;toolbar:false;">useEffect(() => {
const interval = setInterval(() => {
//Call API logic
}, 3600);
return () => clearInterval(interval);
}, [user])</pre>
<p>But when the app is closed and reopened, it again makes a new request to get the token (even though the old token is still valid). So I'm trying to implement functionality that requires an API call to get a new token based on the remaining expiration time. How to implement this function. </p>
<p>I also created a function that calculates the remaining expiration time after the elapsed time</p>
<pre class="brush:php;toolbar:false;">export const calculateRemainingExpirationTime = expirationTime => {
const currentTime = new Date().getTime();
const newExpirationTime = new Date(expirationTime).getTime()
const remainingTime = newExpirationTime - currentTime
return remainingTime; //in milliseconds
};</pre>
<p>So when the page reloads I need to calculate the remaining expiration time and then call the API based on that time and then call the API every 1 hour to get a new token. </p>
<p><strong>I need to implement the following functions</strong></p>
<ol>
<li>When the page reloads, calculate the remaining time and call the API based on the remaining time</li>
<li>Calling API every hour</li>
</ol><p><br /></p>
You need to persist the
expiration time
tolocalStorage
or useRedux-persist
to save