0

The following is just to fetch the time and display it, and using a JS interval timer to invoke a function to set the state, so as to cause the first useEffect() run again to fetch a newer time and update the screen:

export default function App() {
  const [data, setData] = useState({});
  const [timeID, setTimeID] = useState(0);

  useEffect(() => {
    fetch("https://worldtimeapi.org/api/timezone/America/Los_Angeles")
      .then(res => res.json())
      .then(dataFetched => {
        setData(dataFetched);
      });
  }, [timeID]);

  useEffect(() => {
    setInterval(() => {
      console.log("INTERVAL", timeID);
      setTimeID(timeID + 1);
    }, 3000);
  }, []);

  return (
    <div className="App">
      <pre className="data">
        { data.datetime }
      </pre>
    </div>
  );
}

Example: https://codesandbox.io/s/festive-hawking-fjqnd

It is able to update once (after 3 seconds), but the console.log() always showed timeID being 0. I thought the function is a closure and should be able to successfully call setTimeID() and therefore alter the state?

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
nonopolarity
  • 146,324
  • 131
  • 460
  • 740
  • 4
    Change `setTimeID(timeID + 1);` to `setTimeID(timeID => timeID + 1);` – CertainPerformance Feb 08 '21 at 03:46
  • So what you really trying to do is set an interval to fetch a time update every 3 seconds? That would look like ```useEffect(() => { function updateTime() { fetch("https://worldtimeapi.org/api/timezone/America/Los_Angeles") .then((res) => res.json()) .then((dataFetched) => { setData(dataFetched); }); } const interval = setInterval(() => { updateTime(); }, 3000); return () => clearInterval(interval); }, []);``` – Nicholas_Jones Feb 08 '21 at 03:54
  • you mean directly fetching inside of the interval callback? But what if there are tons of things I do in that first useEffect(), and I need the interval just to have variable (state) change to invoke that first useEffect() and using that variable (state) as a dependency? – nonopolarity Feb 08 '21 at 04:00

0 Answers0