i tried the code i attached, and for some reason when i log it the state remains at 5.
i got it working by adding a counter ref but im sure its supposed to work even without it.
pleasse help.
import React , {useEffect, useRef, useState} from 'react';
import styles from "./QuizTimer.module.css";
export default function QuizTimer(props)
{
const timer = useRef();
const [timeRemaining,setTimeRemaining] = useState(5);
const handleTimeRemaining = () => {
console.log(timeRemaining);
if(timeRemaining ===1)
{
setTimeRemaining(5);
}
else{
setTimeRemaining((prev) => {return prev-1;});
}
};
useEffect(() => {
timer.current = setInterval(handleTimeRemaining,1000);
},[]);
return (
<div className={styles.container}>
<h1 >{timeRemaining}</h1>
<p>seconds</p>
</div>
);
}
3
Answers
I think you are looking for something like this
But remember, that you will get a previous value of timer, so you need to log it like this
setInterval
is not precise, consider using the Date object instead see this example:The handleTimeRemaining function was defined when timeRemaining = 5, and it will always remain at timeRemaining = 5 during execution.
That is the reason.