Home > database >  Digital clock made using React not working
Digital clock made using React not working

Time:06-21

I'm learning React from Udemy. When I use the older React version my code is working but with the new 18.1 version, it's not working. I'm trying to build a simple digital clock but sadly not working. Anyone plz help

import React, { useState } from "react";
import logo from './logo.svg';
import './App.css';
function App() {
  setInterval(Time, 1000);
  const date = new Date();
  const time = date.toLocaleTimeString();
  const [uptime, funcTime] = useState(time)
  // event.preventDefault()
  
  function Time() {

    return (
      funcTime(time)
   )
  };
  return (
    <>
      <h1>TIME</h1>
      {uptime}
      {/* <button onClick={Time} type="submit">submit</button> */}
    </>

  )
}
export default App;
<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>

CodePudding user response:

I have moved the time interval to useEffect try this

import React, { useState,useEffect } from "react";
import logo from './logo.svg';
import './App.css';

function App() {
  const date = new Date();
  const time = date.toLocaleTimeString();
  const [uptime, funcTime] = useState(time);

  useEffect(() => {
    const interval = setInterval(() => {
      const newTime = new Date().toLocaleTimeString();
      funcTime(newTime);
    }, 1000);

    return () => {
      clearInterval(interval);
    };
  }, [time]);
  // event.preventDefault()

  return (
    <>
      <h1>TIME</h1>
      {uptime}
      {/* <button onClick={Time} type="submit">submit</button> */}
    </>
  );
}
  • Related