probably a simple answer to my issue, but it is one that I cannot figure out. My countdown keeps on going past zero and into the negatives, I would like it to end when it hits zero. What am I doing wrong?
Thanks!
const [staticCountdown, setStaticCountdown] = useState(15);
const [countdown, setCountdown] = useState(15);
const setCount = (count) => {
if (!props.timerActive) {
setStaticCountdown(count);
setCountdown(count);
}
};
useEffect(() => {
let interval = null;
if (props.timerActive) {
interval = setInterval(() => {
setCountdown(countdown => countdown - 1);
}, 1000);
} else if (!props.timerActive && countdown === 0) {
clearInterval(interval);
}
return () => clearInterval(interval);
}, [props.timerActive, countdown]);
You should change
else if (!props.timerActive && countdown === 0)
into
(if (!props.timerActive || countdown === 0)
here is an example based on you code:
const {
useEffect,
useState
} = React;
function App(){
const [timerActive, setTimerActive] = useState(true);
const handleTimerActive = () => {
setTimerActive((prev) => !prev);
};
return (
<div className="App">
<Timer timerActive={timerActive} />
<button onClick={handleTimerActive}>
{timerActive ? "Stop" : "Run"}
</button>
</div>
);
}
function Timer(props) {
const [countdown, setCountdown] = useState(15);
useEffect(() => {
let interval = null;
if (props.timerActive) {
interval = setInterval(() => {
setCountdown((countdown) => countdown - 1);
}, 1000);
}
if (!props.timerActive || countdown === 0) {
clearInterval(interval);
}
return () => clearInterval(interval);
}, [props.timerActive, countdown]);
const handleReset = () => {
setCountdown(15);
};
return (
<div>
<h1>{countdown}</h1>
<button onClick={handleReset}>Reset</button>
</div>
);
}
ReactDOM.render( <App/> ,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>