react native show current time and update the seconds in real-time

Just move setInterval into componentDidMount function.

Like this :

  componentDidMount() {
    setInterval(() => {
      this.setState({
        curTime : new Date().toLocaleString()
      })
    }, 1000)
  }

This will change state and update every 1s.


in react hooks, it can be done like this:

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

const [dt, setDt] = useState(new Date().toLocaleString());

useEffect(() => {
    let secTimer = setInterval( () => {
      setDt(new Date().toLocaleString())
    },1000)

    return () => clearInterval(secTimer);
}, []);

This method works fine and displays MM/DD/YY hh:mm:ss format

class Clock extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          time: new Date().toLocaleString()
        };
      }
      componentDidMount() {
        this.intervalID = setInterval(
          () => this.tick(),
          1000
        );
      }
      componentWillUnmount() {
        clearInterval(this.intervalID);
      }
      tick() {
        this.setState({
          time: new Date().toLocaleString()
        });
      }
      render() {
        return (
          <p className="App-clock">
            The time is {this.state.time}.
          </p>
        );
      }
    }

original link : https://openclassrooms.com/courses/build-web-apps-with-reactjs/build-a-ticking-clock-component


I got the answer. The code below also works.

componentWillMount(){
    setInterval(function(){
        this.setState({
            curTime: new Date().toLocaleString()
        })
    }.bind(this), 1000);
}