Answer the question
In order to leave comments, you need to log in
How to get data from one component to another?
Hello. 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>
)
}
<Timer callback={callBackTimer} data={timerData}/>
Answer the question
In order to leave comments, you need to log in
Let's say Timer is a component. Then, answer the question:
what does the code above the line refer to?
Read the rules for using hooks in the React documentation! const Timer = ({callback, data}) => {
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question