search

Home  >  Q&A  >  body text

New title: Calculate and update a token's remaining expiration time

<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>
P粉463840170P粉463840170576 days ago651

reply all(1)I'll reply

  • P粉805535434

    P粉8055354342023-08-27 19:30:48

    You need to persist the expiration time to localStorage or use Redux-persist to 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]);

    reply
    0
  • Cancelreply