Listing 6-27: Demonstrating setState's asychronous nature
import {Component} from 'react';
class CounterClass3 extends Component {
constructor(props){
super(props);
this.state = {count:0};
this.testCount = 0;
this.incrementTwice = this.incrementTwice.bind(this);
}
incrementTwice(){
this.setState({count: this.state.count + 1});
this.testCount ++;
this.setState({count: this.state.count + 1});
this.testCount ++;
console.log("Count should be: " + this.testCount);
}
render(){
return(
<button onClick={this.incrementTwice}>{this.state.count}</button>
)
}
}
export default CounterClass3;
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.