Updating State with setInterval in ReactJS

Over the past couple days I’ve begun teaching myself ReactJS. Initially starting with the Official Tutorial on the ReactJS.org homepage, I…

Updating State with setInterval in ReactJS

Over the past couple days I’ve begun teaching myself ReactJS. Initially starting with the Official Tutorial on the ReactJS.org homepage, I then moved on to a Codeacademy’s introductory course on ReactJS. But both beginner courses/tutorials have left me wondering, how do I update state in ReactJS using a timer instead of waiting for users to click buttons triggering onClick events? The tutorials all seem to revolve around updating state when a user clicks a button, which is reasonable, but I really wanted to know how do I automatically update state every 30 seconds or so? After a little digging I found this tutorial here on Medium, Timers in React Apps with Redux by Gustavo Machado. But the code example from Machado’s tutorial is just a snippet and not a fully functional ReactJS app, so I wanted to go ahead and post my modification of Machado’s example for future reference for myself and anybody else here on the ole interwebs. Note that I plan on pinging a server every 30 seconds or so for updates, but for simplicity this example does not include any calls to the server:

import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
timer: null,
counter: 0
};
this.tick = this.tick.bind(this);
}

componentDidMount() {
let timer = setInterval(this.tick, 1000);
this.setState({timer});
}
componentWillUnmount() {
this.clearInterval(this.state.timer);
}

tick() {
this.setState({
counter: this.state.counter + 1
});
}
render() {
return (
<div>Loading{"...".substr(0, this.state.counter % 3 + 1)}
</div>
);
}
}
// ========================================
ReactDOM.render(<App/>, document.getElementById('root'));