update component every second react

Question!

I have been playing around with React and have the following time component that just renders Date.now() to the screen:

import React, { Component } from 'react';

class TimeComponent extends Component {
  constructor(props){
    super(props);

    this.state = { time: Date.now() };
  }
  render(){
    return(
      <div> { this.state.time } </div>
    );
  }
  componentDidMount() {
    console.log("TimeComponent Mounted...")
  }
}

export default TimeComponent;

What would be the best way to get this component to update every second to re-draw the time from a React perspective?



Answers

You need to use setTimeout to trigger the change, but you also need to clear the timer when the component unmounts to prevent it leaving errors and leaking memory:

componentDidMount() {
  this.interval = setInterval(() => this.setState({ time: Date.now() }), 1000);
}
componentWillUnmount() {
  clearInterval(this.interval);
}
By : Waiski


this is react js website example :

var Timer = React.createClass({
  getInitialState: function() {
    return {secondsElapsed: 0};
  },
  tick: function() {
    this.setState({secondsElapsed: this.state.secondsElapsed + 1});
  },
  componentDidMount: function() {
    this.interval = setInterval(this.tick, 1000);
  },
  componentWillUnmount: function() {
    clearInterval(this.interval);
  },
  render: function() {
    return (
      <div>Seconds Elapsed: {this.state.secondsElapsed}</div>
    );
  }
});

ReactDOM.render(<Timer />, mountNode);


In the component's componentDidMount lifecycle method you could set an interval to call a function which updates the state.

 componentDidMount() {
      setInterval(() => this.setState({ time: Date.now(), 1000)
 }
By : erik-sn


This video can help you solving your question :)
By: admin