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?

Idanref
  • 169
  • 1
  • 1
  • 9
  • 2
    If you want to get the current second of time, please use `(new Date()).getSeconds()`, if you do `var today = new Date();` and then `today.getSeconds()`, the value is fixed, so there is no updates. – sam Oct 05 '21 at 00:57
  • If you mean in the useState, then I tried this and still the current second is being displayed but don't update real time. Updated code: `const [seconds, setSeconds] = useState((new Date()).getSeconds());` – Idanref Oct 05 '21 at 01:02
  • `useEffect`, that's the place you update your state. – sam Oct 05 '21 at 01:10
  • I get it now, the solution is so simple I didn't even notice. Thank you so much! – Idanref Oct 05 '21 at 01:16

0 Answers0