Why My Variable "intervalid" Is Not Getting The Value Updated When I Call The Function "stoptimer" Function?
Here is my simple code: import React, { useState } from 'react'; import './App.css'; function App() { const [time, setTime] = useState(0); var intervalId; function startTim
Solution 1:
Because intervalId
is not the same variable that was in scope when startTimer
was invoked. It will be undefined
in all the subsequent renders. ( caused when time
change state )
In React, if you want to "keep a value" across the life cycle of a component, you can use a ref
for it:
// ....var intervalId = React.useRef();
// ....
intervalId.current = setInterval(() => {
// ...clearInterval(intervalId.current);
Solution 2:
Since the App
is invoked everytime you change the state (setTime
), you get a new, fresh value of the local variable.
One of options is to include the variable in your state.
functionApp() {
var [time, setTime] = useState(0);
var [intervalId, setIntervalId] = useState(0);
functionstartTimer() {
setIntervalId(intervalId =>setInterval(() => {
setTime(time => time + 1);
}, 1000));
}
functionstopTimer() {
clearInterval(intervalId);
}
return (
<divclassName="App"><div>{time}</div><div><buttononClick={startTimer}>Start time</button><buttononClick={stopTimer}>Stop time</button></div></div>
);
}
Post a Comment for "Why My Variable "intervalid" Is Not Getting The Value Updated When I Call The Function "stoptimer" Function?"