I want to update the value of a counter variable after some fixed time indefinitely. Here is my code:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
myCount: 1
};
}
// Update state after every 15 seconds.
setTimeout(function(){
this.setState({myCount: this.state.myCount + 1});
}, 15000);
}
However, I get error about unexpected token with this component. How can I set state within the class properly without using any event listeners?
Thanks.
Your call to setTimeout is at the top level of the class body where properties, the constructor, and methods are expected. You can't put arbitrary code there. (Though you could could have a property initializer; not a good idea in this case, though.)
Put it in componentDidMount; and be sure to saved the timer handle (on the instance, usually) and clear the timer in componentWillUnmount so it doesn't fire if the component is unmounted before the timer callback occurs:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
myCount: 1,
};
}
componentDidMount() {
// Update state after every 15 seconds.
this.timerHandle = setTimeout(() => { // ****
this.setState((previousState) => { // ****
return { myCount: previousState.myCount + 1 }; // ****
}); // ****
}, 15000);
}
componentWillUnmount() {
clearTimeout(this.timerHandle);
}
}
Side note: Notice the changes on the **** lines above
this.setState, which is generally best when setting state based on existing state....after some fixed time indefinitely.
A setTimeout callback will only occur once. You may want setInterval if you want the counter updated every 15 seconds. Or alternatively, start a new setTimeout when the callback runs, like this:
startCounterTimer() {
// Update state after every 15 seconds.
this.timerHandle = setTimeout(() => {
this.setState((previousState) => {
this.startCounterTimer(); // ***
return { myCount: previousState.myCount + 1 };
});
}, 15000);
}
componentDidMount() {
this.startCounterTimer();
}