N
N
Ne7Le4Der2022-03-05 14:24:51
React
Ne7Le4Der, 2022-03-05 14:24:51

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]);


But, in the timer function, state endTime is undefined, how to fix it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Goretsky, 2022-03-05
@rqdkmndh

State setting happens asynchronously. Reading the documentation
Why does setState give an incorrect value?

B
black1277, 2022-03-05
@black1277

Add a log immediately after setting the new state:

setEndTime(endTimeUnix * 1000);
console.log('endTime', endTime);
const timerInterval = setInterval(timer, 1000);

You will see endTime is undefined. Because setting a new state does not guarantee that it will happen immediately, but it guarantees a new value on the next render.
If you still want to do something right after setting a new state, then you can rewrite the component in a class style - there, this.setState has a callback function as the second parameter, which is executed after setting the new state value.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question