0

As I am learning react at the moment I came across this concept of event handler using "setState".

It is a little complicated for my understanding as 3 functions within each other. Case in point.

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

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

//....some other code

This code works. I tried to understand the increment function a little further but I can't understand why the following code will not work:

increment(){
  this.setState(function anon(state){
    count: state.count+1
    })
}

What is wrong with this code?

BitByBit
  • 567
  • 4
  • 16
  • 3
    the 2nd function has no return value – Krzysztof Krzeszewski May 25 '21 at 07:15
  • @KrzysztofKrzeszewski also missing second pair of `{` and `}` for object/function body. – VLAZ May 25 '21 at 07:19
  • Duplicate: [When should I use a return statement in ES6 arrow functions](https://stackoverflow.com/questions/28889450/when-should-i-use-a-return-statement-in-es6-arrow-functions) –  May 25 '21 at 07:26

2 Answers2

2
function anon(state) {
  count: state.count + 1
}

^ This function is neither creating an object, nor returning anything from the function. It is creating a label called count inside the function. So, it is not throwing a syntax error.

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

^ This callback creates an object with count key and implicitly returns it. It is equivalent to the following code when you use a regular function

this.setState(function (state) => {
   return { count: state.count+ 1 }
})
adiga
  • 34,372
  • 9
  • 61
  • 83
0

The only missing part is return.

increment(){
  this.setState(function anon(state){
    return {count: state.count+1}
    })
}
Charlie
  • 22,886
  • 11
  • 59
  • 90