I’m trying to pass data to the callback function, but for some reason it breaks everything and I always get the timer by zeros:
const [timerData, setTimerData] = useState({
seconds: 0
minutes: 0
hours: 0
});
const callBackTimer = data => setTimerData(data);
useEffect(() => {
console log(timerData);
},[timerData])
const Timer = ({callback, data}) => {
const [seconds, setSeconds] = useState(data.seconds);
const [minutes, setMinutes] = useState(data.minutes);
const [hours, setHours] = useState(data.hours);
const [isActive, setIsActive] = useState(clients.length > 1);
let toggle = () => {
setIsActive(!isActive)
}
let reset = () => {
setSeconds(0);
setIsActive(false);
}
useEffect(() => {
let interval = null;
if (isActive) {
interval = setInterval(() => {
if(seconds < 60) setSeconds(seconds => seconds + 1);
else {
setSeconds(0);
if(minutes < 60) setMinutes(minutes => minutes + 1);
else {
setMinutes(0);
setHours(hours => hours + 1);
}
}
console.log({hours, minutes, seconds});
callback({hours, minutes, seconds});
}, 1000);
} else if (!isActive && seconds !== 0) {
clearInterval(interval);
}
return() => clearInterval(interval);
}, [isActive, seconds, minutes, hours, timerData]);
return(
<div className={'timer'}>
<h1>{seconds}</h1>
<h1>{minutes}</h1>
<h1>{hours}</h1>
</div>
)
}
My callback function not working and timer not updated.
I call the timer like this:
<Timer callback={callBackTimer} data={timerData}/>
Please tell me what I did wrong. Thanks.