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);
}
}
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>
)
}
<Timer callback={data => setTimerData(data)} data={timerData}/>