'React Auto Increment counter
I replicated this code entirely from a Youtube React tutorial I was following. But the result they got and what i got are entirely different.
class Contact extends Component {
constructor(props) {
super(props);
this.state = { counter: 0 };
}
increment() {
setTimeout(() => {
this.setState((prev,props)=>({ counter: prev.counter + 1 }));
}, 3000);
}
render() {
this.increment();
return (
<div>
<p>{this.state.counter}</p>
</div>
);
}
}
export default Contact;
result intended: 1 2 3 4 5 6 7 8 9 10 11 12 .....
Result obtained: 2 4 6 8 12 18 26 34 42 50 56 66 ....
Solution 1:[1]
You're calling increment() inside render() so that the interval function is initialized over and over again resulting in unpredictable behaviour.
You need to guarantee, the interval is only initialized once. Therefor you can use the lifecycle hook componentDidMount() which is executed once the component is mounted. With intervals and timeouts you should also make sure to clear them at unmount. componentWillUnmount() is the tool for this task.
Following a working solution:
class Contact extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
this.interval = null;
}
componentDidMount() {
this.interval = setInterval(() => {
this.setState({
count: this.state.count + 1,
});
}, 3000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return <div>{this.state.count}</div>;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
