Answer the question
In order to leave comments, you need to log in
Why is state not available in interval?
I'm trying to make a timer, the code is as follows
const [endTime, setEndTime] = useState<number>();
const [timerValue, setTimerValue] = useState<Time>({
hours: 0,
minutes: 0,
seconds: 0
});
useEffect(() => {
const endTimeUnix = timestamp + minutesLimit * 60;
setEndTime(endTimeUnix * 1000);
const timerInterval = setInterval(timer, 1000);
return () => clearInterval(timerInterval);
}, [timestamp, minutesLimit]);
Answer the question
In order to leave comments, you need to log in
State setting happens asynchronously. Reading the documentation
Why does setState give an incorrect value?
Add a log immediately after setting the new state:
setEndTime(endTimeUnix * 1000);
console.log('endTime', endTime);
const timerInterval = setInterval(timer, 1000);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question