简体   繁体   中英

Problem with Update in Every Refresh, localStorage, useState, useEffect

I am trying to prevent my app to go into useEffect hook and implement what is inside within a 5 second period regardless of the situation the page is refreshed or not.

My code still only fires up the useEffect hook only on page refresh. It does not really care whether 5 seconds passed it fires up in every page refresh and then does not do anything for an eternity unless you refresh the page again. It acts like a useEffect hook with empty dependency array.

How can I achieve useEffect hook to run every 5 seconds regardless the page is refreshed or not? Here is my snippet.

  const localVisitTime = localStorage.getItem('localVisitTime');
  const currentTime = new Date().getTime();
  const timeDifference = currentTime - localVisitTime;

  const [ visitTime, setVisitTime ] = useState(localVisitTime);

  if (localVisitTime && timeDifference <= 5000) {
    // Do nothing, wait!
  } else {
    localStorage.setItem('localVisitTime', new Date().getTime());
    setVisitTime(localVisitTime);
  }

  useEffect(() => {

    const fetchData = async () => {
      console.log('Data fetched!');
    }

    fetchData();
  }, [visitTime]);

The reason it is not firing multiple times is the check for time difference happence only once, you should use a set interval which checks every second if the time is valid and tries to set the time difference in a state, but i think its not necessary.

I believe you want to maintain this 5 seconds firing even between page refreshes but if its not critical, you can always start again when the page refreshes. I think you should use the set interval and not worry about refreshes like this.

const fetchData = async () => {
  console.log("Data fetched!");
};

useEffect(() => {
  fetchData();
  const interval = setInterval(() => {
    fetchData();
  }, 5000);
  return () => clearInterval(interval);
}, []);

This way, the fetch data will run every 5 seconds, and will run on every refresh

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM