V
V
Vladimir2022-02-26 11:09:52
React
Vladimir, 2022-02-26 11:09:52

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>
    )
  }


I call the timer like this:

<Timer callback={callBackTimer} data={timerData}/>

Please tell me what I did wrong. Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Goretsky, 2022-02-26
@rqdkmndh

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 question

Ask a Question

731 491 924 answers to any question