I am unable to access state in a React functional component from a setInterval or setTimeout callback.
A very simple example updating state in one interval and attempting to access state with bound function and unbound arrow interval callbacks.
https://codesandbox.io/s/pedantic-sinoussi-ycxin?file=/src/App.js
const IntervalExample = () => {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval1 = setInterval(() => {
setSeconds((seconds) => seconds + 1);
}, 1000);
const interval2 = setInterval(() => {
// this retrieves only the initial state value of 'seconds'
console.log("interval2: seconds elapsed", seconds);
}, 1000);
const interval3 = setInterval(function () {
// this retrieves only the initial state value of 'seconds'
console.log("interval3: seconds elapsed", seconds);
}, 1000);
return () => {
clearInterval(interval1);
clearInterval(interval2);
clearInterval(interval3);
};
}, []);
return (
<div className="App">
<header className="App-header">
{seconds} seconds have elapsed since mounting.
</header>
</div>
);
};
I would like to make this work in both function and arrow cases. Any help appreciated.
Thanks