skip to Main Content

I am making a simple clock, but want data to be in a single object (Rather than making 3 different states for hours, minutes and seconds. This way its more meaningful. But I am getting error. Pls help.

import React from "react";
import { useState } from "react";

export default function Ex6() {

    const date = new date();
    const [time, setTime] = useState({hours:'00', minutes:'00', seconds:'00'});

    const updatetime = () => {
        setTime({hours:date.getHours(), minutes:date.getMinutes(), seconds: date.getSeconds()});
    }

    updatetime();

    return (
        <div>
            <p>{time.hours}:{time.minutes}:{time.seconds}</p>
        </div>
    )
}

Error:

enter image description here

2

Answers


  1. Please change to new date() ==> new Date().

    You must use the useEffect.

    example

    import { useEffect, useState } from "react";
    
    const Time = () => {
      const date = new Date();
      const [time, setTime] = useState({
        hours: "00",
        minutes: "00",
        seconds: "00",
      });
    
      useEffect(() => {
        const updatetime = () => {
          setTime({
            hours: date.getHours(),
            minutes: date.getMinutes(),
            seconds: date.getSeconds(),
          });
        };
        updatetime();
      }, []);
    
      return (
        <div>
          <p>
            {time.hours}:{time.minutes}:{time.seconds}
          </p>
        </div>
      );
    };
    
    export default Time;
    
    
    

    I’m not good at English, so I used a translator

    Login or Signup to reply.
  2. change the variable name to something else

     import React from "react";
     import { useState } from "react";
    
    export default function Ex6() {
    
    const currentDate = new Date();
    const [time, setTime] = useState({hours:'00', minutes:'00', seconds:'00'});
    
    const updatetime = () => {
        setTime({hours:date.getHours(), minutes:date.getMinutes(), seconds: date.getSeconds()});
    }
    
    updatetime();
    
    return (
        <div>
            <p>{time.hours}:{time.minutes}:{time.seconds}</p>
        </div>
    )
    

    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search