Home > Back-end >  How to auto-refresh time in React when using 'date-fns' library
How to auto-refresh time in React when using 'date-fns' library

Time:10-07

I am working on my personal Portfolio using React and I want to add a statement on the landing page that displays my local time and timezone to recruiters, as seen below: Time

I have implemented this using the date-fns library but I am currently facing one issue. As time goes by, the time values on the screen stay constant and do not update themselves automatically. As we speak, it is currently 16:58 but the time still shows 16:47. I have to do a manual refresh for the updated time values to show. I want to implement this in such a way that the time will update every 60 seconds and show the current time always.

I wrote this Class component to implement the feature:

export class Time extends Component {

  constructor() {
  super();
    var today = new Date();

    var time = format(today, 'HH:mm')

    this.state = {

      currentTime: time

    }

  }

   
  render() {
    return (
      <div className="time">
        <p>
          My Local Time is { this.state.currentTime } GMT  3
        </p>
      </div>
    );
  }

}

setInterval(Time, 60000);

What could I do to make this possible?

CodePudding user response:

Create a componentDidMount method, and place the setInterval in there. Make sure that the setInterval updates this.state.currentTime. It's also a good idea to clear the interval afterwards, so store the interval id and then call clearInterval in componentWillUnmount.

Something like this

export class Time extends Component {
    intervalId

    constructor() {
        super()
        var today = new Date()

        var time = format(today, "HH:mm")

        this.state = {
            currentTime: time,
        }
    }

    componentDidMount() {
        var today = new Date()

        var time = format(today, "HH:mm")

        intervalId = setInterval(() =>
            this.setState({
                currentTime: time,
            }),
            60000
        )
    }

    componentWillUnmount() {
        clearInterval(intervalId) // Clear interval to prevent memory leaks
    }

    render() {
        return (
            <div className="time">
                <p>My Local Time is {this.state.currentTime} GMT  3</p>
            </div>
        )
    }
}


I would suggest that you read up on the React Docs, since these are the basics of React.

CodePudding user response:

I tried using the solution provided Luke-shang-04 but I ran into issues with declaration of the intervalId variable. I therefore resorted to using React Hooks and converted this component into a Functional component.

The code below works:

export const Time = () => {
   

  const [time, setTime] = useState(new Date());

  useEffect(
    () => {
      const intervalId = setInterval(() => {
      
        setTime(new Date());
      }, 60000);
      return () => {
        clearInterval(intervalId)
      }
    } 
  )

  return(
    <div>
      <p>{`My local time is ${format(time, 'HH:mm')} GMT 3`} </p>
    </div>
  )

}
  • Related