lundi 4 octobre 2021

React - Live Clock Doesn't Work With Initial Value Different Than 0

I am trying to build a live clock with react for a weather app that will update the time in real time instead of only while refreshing the page.

I managed to update the clock in real time but the problem is that it works only when initial value in useState is set to 0.

Declerations:

var today = new Date();
const [seconds, setSeconds] = useState(0);

useEffect:

useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(today.getSeconds());
    }, 1000);
    return () => clearInterval(interval);
  }, [seconds]);

This code works great, the problem is that since the initial value is 0 - the seconds jump from 0 to 37 for example and only then start updating.

When I try to change the initial value for instance:

const [seconds, setSeconds] = useState(today.getSeconds());

The clock starts with the correct second, but doesn't keep updating real time - the clock is stuck.

Any idea?




Aucun commentaire:

Enregistrer un commentaire