0

In React.js, I want to make a simple count button, where each click is a +1, but on the first click it still gives me 0, and only on the second click does it go up to 1, why is that? And how do I fix it?

class COUNT extends React.Component{
    constructor(props){
        super(props);
        this.state = { count : 0 }
    }

    addNumber(){
        setState({count: this.state.count+1})
        console.log(this.state.count)
    }
    
    render(){
        return(
            <button onClick={() => addNumber()}>button</button>
        )
    }
}
juliomalves
  • 42,130
  • 20
  • 150
  • 146
BarakOren
  • 99
  • 1
  • 8
  • You seem to be using `setState` a bit wrong. Try this `setState({count: this.state.count + 1})` Further more, seems like you are setting state based on previous states (newCount = previousCount + 1), I recommend using [function-style `setState`: `setState(prev => ({count: prev.count + 1}))`](https://stackoverflow.com/questions/42494985/setstate-in-react-based-on-current-state) – Bao Huynh Lam Jul 11 '21 at 16:05
  • @BaoHuynhLam yeah my bad i wrote it wrong here thanks – BarakOren Jul 11 '21 at 16:07
  • I edited your question because it looks like a feature you want to implement! – Dory Nguyen Jul 11 '21 at 16:10
  • @barakooren There is danger using `console.log` immediately after setting states, because `setState` is asynchronous by nature. If your error stems from the `console.log` line, you might want to take a look at my post on a similar problem here: https://stackoverflow.com/a/68335232/14426823 – Bao Huynh Lam Jul 11 '21 at 16:12

1 Answers1

0

I find it unlikely that this code works at all. Perhaps a copy/paste error? There were multiple missing this's and (as stated in a comment) a missing count:. I believe this should work:

class COUNT extends React.Component{
  constructor(props){
    super(props);
    this.state = { count : 0 }
  }

  addNumber(){
    this.setState({state: this.state.count+1})
    console.log('added', this.state.count) // likely prints old value
  }

  render(){
    console.log('rendering', this.state.count) // should print new value
    return(
      <button onClick={() => this.addNumber()}>button {this.state.count}</button>
    )
  }
}

Note that setState will not generally immediate change this.state; it queues an update. See the comments around console.logs. This is maybe what you were seeing with the logs being one number out of date. I've added a rendering of the count ({this.state.count} in the button) to make it clear that it does have the correct value.

edemaine
  • 2,699
  • 11
  • 20