0

I can't figure out what's going on here. I have this code

setIdleEvent(setTimeout(onIdle, idleTimeout)); 
console.log('idleEvent', idleEvent);

idleEvent is a state, defined as const [idleEvent, setIdleEvent] = useState<NodeJS.Timeout>(); After executing this code, idleEvent is undefined.

So I tried this

const foo = setTimeout(onIdle, idleTimeout);
console.log('foo:', foo); 
setIdleEvent(foo);
console.log('idleEvent', idleEvent);

Foo has a numeric value, but idleEvent is still undefined. What's going on?

enter image description here

Peter Kronenberg
  • 878
  • 10
  • 32
  • 1
    The code is working, you just have your log statement in a spot where it isn't useful. Calling `setIdleEvent` does not change the value of the local const `idleEvent` (it's a const, it *can't* change). Instead, it instructs react to rerender the component. On the next render, a new const will be created with the new value, but your log statement in the previous render has no access to that. If you'd like to verify that the component is rerendering, put a log statement in the body of the component. – Nicholas Tower Nov 14 '21 at 16:39
  • Thanks! I'm relatively new to react and still learning some of these nuances – Peter Kronenberg Nov 14 '21 at 16:51

0 Answers0