Answer the question
In order to leave comments, you need to log in
How to pass state from a component to another state to store?
Hello. I know what is googled - contexts, props and so on, but I have functions and I don’t understand how to implement it specifically here. I try with a callback function like this:
const [timerData, setTimerData] = useState({
seconds: 0,
minutes: 0,
hours: 0
});
const callBackTimer = useCallback(setTimerData, [timerData]);
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question