New title: Calculate and update a token's remaining expiration time
P粉463840170
P粉463840170 2023-08-26 23:13:42
0
1
511

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

  1. When the page reloads, calculate the remaining time and call the API based on the remaining time
  2. Calling API every hour


P粉463840170
P粉463840170

reply all (1)
P粉805535434

You need to persist theexpiration timetolocalStorageor useRedux-persistto save

//此间隔仅在用户未关闭应用程序时执行 useEffect(() => { const interval = setInterval(() => { //调用api逻辑 //将过期时间写入本地存储 localStorage.setItem("expir",value) }, 3600); return () => clearInterval(interval); }, [user])
//获取在本地存储中写入/存储的过期时间 React.useEffect(() => { let mounted = true; const getToken = () => { if (mounted) { const expirationtime = localStorage.getItem("expir"); if (new Date() > new Date(Number(expirationtime))) { // 过期,获取新的令牌 } else { // 存在的令牌 } } }; getToken(); return () => { mounted = false; }; }, [user]);
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!