Listing 6-28: Using the updater function with setState
import {Component} from 'react';
class CounterClass4 extends Component {
constructor(props){
super(props);
this.state = {count:0};
this.testCount = 0;
this.incrementTwice = this.incrementTwice.bind(this);
}
incrementTwice(){
this.setState((current)=>{return {count: current.count + 1};});
this.testCount++;
this.setState((current)=>{return {count: current.count + 1};});
this.testCount++;
console.log("Count should be: " + this.testCount);
}
render(){
return(
<button onClick={this.incrementTwice}>{this.state.count}</button>
)
}
}
export default CounterClass4;
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.