Search code examples
reactjsuse-state

How do I display the objects inside a useState state in the return?


import React, { useState , useEffect} from 'react';

function Counter(){
    const targetDate = '1 Jan 2023';
    const target = new Date(targetDate);
    const currDate = new Date();

    const targetTime = target.getTime();
    const currDateTime = currDate.getTime();

    const time = targetTime - currDateTime;

    var seconds = Math.floor((time % (1000*60)) / 1000);
    var minutes = Math.floor((time % (1000*60 * 60)) / (1000 * 60));
    var hours = Math.floor((time % (1000 * 60 * 60 * 24)) / (100 * 60 * 60));
    var days = Math.floor(time / (1000*60*60*24));

    const [ctime , setCTime] = useState({seconds , minutes , hours , days});

    useEffect(() =>{
        const interval = setInterval(() => setCTime(ctime) , 1000);
        return () => clearInterval(interval);
    })
    return(
        <div>
            <h1>Countdown</h1>
            {ctime}
        </div>
    )
}

export default Counter;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

This is my code up to this point, I have all the values I need to display calculating as I want them, but since I'm learning hooks and how to use them, I cant figure out how to display the values from the state.

The error I'm getting is "Error: Objects are not valid as a React child (found: object with keys {seconds, minutes, hours, days}). If you meant to render a collection of children, use an array instead."


Solution

  • I thought that you want to make a countdown timer. And I wrote similar with suitable react codes.

    function Counter() {
      // initial state is 0 for all
      const [ctime, setCTime] = useState({
        seconds: 0,
        minutes: 0,
        hours: 0,
        days: 0,
      });
    
      // Do not use global variables if you don't need to
      const startCountDown = () => {
        const targetTime = new Date("1 Jan 2023").getTime();
        const currDateTime = new Date().getTime();
        const time = targetTime - currDateTime;
    
        const s = Math.floor((time % (1000 * 60)) / 1000);
        const m = Math.floor((time % (1000 * 60 * 60)) / (1000 * 60));
        const h = Math.floor((time % (1000 * 60 * 60 * 24)) / (100 * 60 * 60));
        const d = Math.floor(time / (1000 * 60 * 60 * 24));
    
        setCTime({ seconds: s, minutes: m, hours: h, days: d });
      };
    
      useEffect(() => {
        const interval = setInterval(() => startCountDown(), 1000);
        return () => clearInterval(interval);
      });
    
      return (
        <div>
          <h1>Countdown</h1>
          <div>
            {ctime.days}:{ctime.hours}:{ctime.minutes}:{ctime.seconds}
          </div>
        </div>
      );
    }