Seconds Static in React Time Implementation

Viewed 239

I have a javascript Time function inside my React App component and everything is working well. But the main issue is I needed my seconds to keep on counting instead of standing static until the page is refresh.

Have tried several attempts but still not working. What I have presently is attached below.

My code is here below.

App.js

import React, { Component } from 'react'

export class App extends Component {
  constructor(props) {
    super(props)
  
    this.state = {
       
    }
  }
  

render() {
   
  function getDateTime() {
      let now     = new Date(); 
      let year    = now.getFullYear();
      let month   = now.getMonth()+1; 
      let day     = now.getDate();
      let hour    = now.getHours();
      let minute  = now.getMinutes();
      let second  = now.getSeconds(); 
      if(month.toString().length === 1) {
           month = '0'+month;
      }
      if(day.toString().length === 1) {
           day = '0'+day;
      }   
      if(hour.toString().length === 1) {
           hour = '0'+hour;
      }
      if(minute.toString().length === 1) {
           minute = '0'+minute;
      }
      if(second.toString().length === 1) {
           second = '0'+second;
      }   
      var dateTime = hour+':'+minute+':'+second;   
       return dateTime;
  }

    return( 
  <div>
  
    {<h2>The time is {getDateTime()}</h2>}

 
  
  </div>
  )}
}

export default App


Index.js


import React from "react";
import ReactDOM from "react-dom";

import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  rootElement
);


2 Answers

I described the solution in a comment, but here's a jsfiddle with more detail:

The idea here would be to store the time in the state, and to update the state every time you want the timer to update. The place to set a setInterval inside stateful components is usually componentDidMount

https://jsfiddle.net/nfr6phw2/

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
        datetime: new Date()
    }
  }
  
  componentDidMount() {
    setInterval(() => {
        this.setState({datetime: new Date()})
    }, 1000);   
  }
  
  getDateTime() {
      let now     = new Date(); 
      let year    = now.getFullYear();
      let month   = now.getMonth()+1; 
      let day     = now.getDate();
      let hour    = now.getHours();
      let minute  = now.getMinutes();
      let second  = now.getSeconds(); 
      if(month.toString().length === 1) {
           month = '0'+month;
      }
      if(day.toString().length === 1) {
           day = '0'+day;
      }   
      if(hour.toString().length === 1) {
           hour = '0'+hour;
      }
      if(minute.toString().length === 1) {
           minute = '0'+minute;
      }
      if(second.toString().length === 1) {
           second = '0'+second;
      }   
      var dateTime = hour+':'+minute+':'+second;   
       return dateTime;
  }
  
  render() {
    return (
      <div>
        <h2>The time is {this.getDateTime()}</h2>
      </div>
    )
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#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>
<div id="app"></div>

In here you can use state management in react and a timer function. So after every 1000ms, it retrieve value from getDateTime function and update the state. So when the state changed, page is rendering. I have updated your code. Please check

import React, { Component } from "react";

export class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      dateTime: ""
    };
  }

  getDateTime = () => {
    let now = new Date();
    let year = now.getFullYear();
    let month = now.getMonth() + 1;
    let day = now.getDate();
    let hour = now.getHours();
    let minute = now.getMinutes();
    let second = now.getSeconds();
    if (month.toString().length === 1) {
      month = "0" + month;
    }
    if (day.toString().length === 1) {
      day = "0" + day;
    }
    if (hour.toString().length === 1) {
      hour = "0" + hour;
    }
    if (minute.toString().length === 1) {
      minute = "0" + minute;
    }
    if (second.toString().length === 1) {
      second = "0" + second;
    }
    var dateTime = hour + ":" + minute + ":" + second;
    return dateTime;
  };

  componentDidMount() {
    this.myInterval = setInterval(() => {
      this.setState({ dateTime: this.getDateTime() });
    }, 1000);
  }

  render() {
    return <div>{<h2>The time is {this.state.dateTime}</h2>}</div>;
  }
}

export default App;
Related