Search code examples
reactjssingle-page-applicationreload

Reload React application every minute for five minutes


Is there a simple way to reload the React application with window.location.reloadevery minute for five minutes if the user stays on that specific site. If the user goes to the home page of the application it should not refresh the page if time is left.

I tried something like

import React, { useEffect, useState } from 'react';

const RefreshComponent = () => {
  const [refreshCount, setRefreshCount] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      if (refreshCount < 5) {
        window.location.reload();
        setRefreshCount(refreshCount + 1);
      }
    }, 60000); // 60000 milliseconds = 1 minute

    // Stop refreshing after 5 minutes
    setTimeout(() => {
      clearInterval(interval);
    }, 300000); // 300000 milliseconds = 5 minutes

    return () => clearInterval(interval); // Clean up interval on component unmount
  }, [refreshCount]);

  return (
    <div>
      <h1>Auto Refresh Component</h1>
      <p>Refreshing in {5 - refreshCount} minutes</p>
    </div>
  );
};

export default RefreshComponent;

But this actually will refresh the page forever.


Solution

  • Maybe what you need is the expiration time rather than the timer:

    
    const RefreshComponent = () => {
      useEffect(() => {
        const expires = Number(localStorage.getItem('Expires') ?? Date.now() + 5 * 60 * 1000);
        localStorage.setItem('Expires', expires.toString());
    
        let tid: number | undefined;
        let timeLeft = expires - Date.now();
        const countdown = (t: number) => {
          if (timeLeft > 0) {
            tid = window.setTimeout(() => {
              window.location.reload();
              timeLeft = timeLeft - t;
              countdown(60 * 1000);
            }, t);
          } else {
            localStorage.removeItem('Expires');
          }
        };
        countdown((timeLeft % (60 * 1000)) || 60 * 1000);
        return () => {
          clearTimeout(tid);
        };
      }, []);
    
      return (
        <div>
          <h1>Auto Refresh Component</h1>
        </div>
      );
    };
    
    export default RefreshComponent;