I'm following a beginner's tutorial for the useState and useRef hooks, trying to implement a simple timer in react.
I'm using the interval variable to store the value from setInterval()
On click of start button, I am able to console.log the value of the interval correctly.
However on click of stop button, interval.current is console logged as undefined. The stopTimer() hence does not function as expected.
Why does interval.current print undefined when it is clearly set in startTimer (and logged there)? What am I missing here?
import React, { useState, useRef } from 'react';
const pad = (time) => {
return time.toString().padStart(2, "0");
};
function App() {
const [title, setTitle] = useState("Pomodoro!");
const [timeLeft, setTimeLeft] = useState(5);
const interval = useRef(null);
const startTimer = () => {
interval.current = setInterval(() => {
setTimeLeft((timeLeft) => {
if (timeLeft >= 1) {
return timeLeft - 1;
}
return 0;
});
}, 1000);
console.log(interval.current, " :in start");
}
const stopTimer = (interval) => {
console.log("in stop: ", interval.current);
clearInterval(interval.current);
}
const resetTimer = () => { }
const minutes = pad(Math.floor(timeLeft / 60));
const seconds = pad((timeLeft - minutes * 60));
return (
<div>
<div>{title}</div>
<div>
<span>{minutes}</span>
<span>:</span>
<span>{seconds}</span>
</div>
<div>
<button onClick={startTimer}>Start</button>
<button onClick={stopTimer}>Stop</button>
<button onClick={resetTimer}>Reset</button>
</div>
</div>
);
}
export default App;
output in console
6 " :in start" in stop: undefined
Thanks