I need to refresh Spotify token every hour in React application (Spotify token is valid for 1 hour). I know the following method uses useEffect hook and setInteral
useEffect(() => { const interval = setInterval(() => { //Call API logic }, 3600); return () => clearInterval(interval); }, [user])
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.
I also created a function that calculates the remaining expiration time after the elapsed time
export const calculateRemainingExpirationTime = expirationTime => { const currentTime = new Date().getTime(); const newExpirationTime = new Date(expirationTime).getTime() const remainingTime = newExpirationTime - currentTime return remainingTime; //in milliseconds };
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.
I need to implement the following functions
You need to persist the
expiration time
tolocalStorage
or useRedux-persist
to save