Answer the question
In order to leave comments, you need to log in
Why doesn't useState change its value in setInterval?
const [stroke, setStroke] = useState(0);
const updateStroke = () => {
let timer = setInterval(() => {
if (stroke > 1250) {
setStroke(1256);
clearInterval(timer)
}
console.log(stroke);
setStroke(stroke => stroke + 250);
}, 1000);
};
<svg
className="loadingRing"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
onClick={() => updateStroke()}
>
<circle
r="200"
cx="210"
cy="210"
style={{ strokeDashoffset: stroke }}
/>
</svg>
Answer the question
In order to leave comments, you need to log in
When the timer was created, the stroke value was 0, which falls into the closure. Calls to setStroke change the value in the hook, of course, but the variable in the closure doesn't change.
It is necessary to bring all the logic "inside" setStroke.
const updateStroke = () => {
let timer = setInterval(() => {
setStroke(stroke => {
console.log(stroke);
if (stroke > 1250) {
clearInterval(timer);
return 1256;
} else {
return stroke + 250;
}
});
}, 1000);
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question