Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JS - Live clock update

I've got a clock function that gets time and renders out the hours, minutes and seconds, and I'm trying to update the data on screen in real time, but for some reason my setInterval function isn't doing what I expect.

I thought react's render method is supposed to render data in real time. Do I need ajax for this? Can anyone offer some advice?

var CityRow = React.createClass({

  render: function() {

    var currentdate = new Date();

    function getTime() {
      // get local time based on the UTC offset
      this.hours = currentdate.getUTCHours() + parseInt(this.props.UTCOffset);    

      // correct for number over 24, and negatives
      if( this.hours >= 24 ){ this.hours = this.hours - 24; }
      if( this.hours < 0   ){ this.hours = this.hours + 12; }

      // add leading zero, first convert hours to string
      this.hours = this.hours + "";
      if( this.hours.length == 1 ){ this.hours = "0" + this.hours; }

      // minutes are the same on every time zone
      this.minutes = currentdate.getUTCMinutes();

      // add leading zero, first convert hours to string
      this.minutes = this.minutes + "";
      if( this.minutes.length == 1 ){ this.minutes = "0" + this.minutes; }

      this.seconds = currentdate.getUTCSeconds();
    }

    window.setInterval(function () {
      getTime();
    }, 1000);

    return(
      <div className="city-row" ref="cityRow">
        <span className="city-time">{this.hours}:{this.minutes}:{this.seconds}</span>
        </div>
      </div>
    )
  }
});
like image 238
amoeboar Avatar asked Oct 01 '15 06:10

amoeboar


1 Answers

The official React Docs describe exactly what you need (and even explains why you should do it as described):

--> React Docs: State and Lifecycle

Example on CodePen:

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);
like image 160
KevinH Avatar answered Nov 08 '22 20:11

KevinH