3

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

Nesh
  • 2,389
  • 7
  • 33
  • 54
  • 1
    Great stuff including all the necessary code and not a lot of extraneous code! Most people get that wrong. :-) Next time, rather than an off-site resource like codepen, please make your runnable example runnable **here, on-site** using Stack Snippets. Stack Snippets support React, including JSX; [here's how to do one](http://meta.stackoverflow.com/questions/338537/). – T.J. Crowder Mar 22 '19 at 15:53
  • 1
    @T.J.Crowder ahha thx for the stack snippet :) – Nesh Mar 22 '19 at 16:41

3 Answers3

2

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
   }))
}
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
2
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
}))
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
1

The problem is in setCount(), where you miss a pair of parenthesis! Here's the correct version:

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

There are two parenthesis more! One right after the => and one at then of the this.setState() call.

Jolly
  • 1,678
  • 2
  • 18
  • 37