Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to increment count using state in react [duplicate]

Following is my code in which I am trying to increment the count using click button but it's not updating the value. Though I am not getting any error in console as well. Let me know what I am doing wrong here.

JS Code -

class App1 extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      count: 0
    }
    this.setCount = this.setCount.bind(this)
  }

  setCount() {
    this.setState((state) => {
      count: state.count + 1
    })
  }



  render() {
    return (
      <>
        <hr />
        <h3>test increment</h3>
        <button onClick={this.setCount}>Click</button>
      <p>{this.state.count}</p>
      </>
    )
  }
}

ReactDOM.render(<App1 />, document.getElementById('root'))

Codepen - https://codepen.io/anon/pen/LaMOEp

like image 615
Nesh Avatar asked Apr 07 '26 01:04

Nesh


2 Answers

You are not returning anything. You could use return in side callback.

setCount() {
    this.setState((state) => {
       return {count: state.count + 1}
    }))
  }

Or you can use avoid using of return wrapping you return value in () after =>

setCount() {
   this.setState((state) => ({
      count: state.count + 1
   }))
}
like image 122
Maheer Ali Avatar answered Apr 09 '26 14:04

Maheer Ali


this.setState((state) => {
  count: state.count + 1
})

In the above code, the curly brackets are the body of the function, count: is a line label, and state.count + 1 is an expression that never gets used. If you want to use the concise arrow function syntax to return an object literal, then you need to wrap the object in parentheses:

this.setState((state) => ({
  count: state.count + 1
}))
like image 26
Nicholas Tower Avatar answered Apr 09 '26 15:04

Nicholas Tower



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!