0

I have a project that uses a class component to count the number of button presses. I got it to work, but when I console.log the count value, it returns a number one lower than the number displayed, even though they are using the same reference. I expected them to be the same number.

class ButtonCounter extends React.Component {
            constructor() {
                super()
                this.state = {
                    count: 0
                }
            }
            counter = 0
            getCount = () => {
                console.log('giving count')
                return this.counter
            }
            setCount = (amnt) => {
                this.counter += amnt
                this.setState({
                    count: this.counter
                })
                console.log(this.state.count) // returns -1 than the displayed value
            }
            render(){
                return(
                    <div>
                        <button onClick = {() => this.setCount(1)}>{this.state.count}</button>
                    </div>
                )
            }
        }

image of the code in browser

pilchard
  • 12,414
  • 5
  • 11
  • 23

1 Answers1

0

As stated in react docs

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied

Source: https://reactjs.org/docs/react-component.html#setstate

Raghav Bhardwaj
  • 153
  • 1
  • 7