1

I am trying to understand the below syntax in my React app. Essentially I wanted to understand the code inside setState()

this.getSomePromise().then(
      // resolve callback function
      someImg =>
        this.setState(prevState => ({
          ...prevState,
          doggo: someImg.message
        })),
      // reject callback function
      () => alert("Rejected!")
    );

What I was expecting was a syntax like this;

    this.setState(prevState => {
// some code
    })

But the round bracket immediately after prevState => is getting me confused.

copenndthagen
  • 49,230
  • 102
  • 290
  • 442
  • `const foo = () => {}` with `foo() // returns undefined`, instead `const bar = () => ({})` with `bar() // return an empty object {}` – Federkun Feb 10 '19 at 08:25
  • Possible duplicate of [How is () => {...} different from () =>](https://stackoverflow.com/questions/52334319/how-is-different-from) and [When should I use `return` in es6 Arrow Functions?](https://stackoverflow.com/questions/28889450) – adiga Feb 10 '19 at 08:27
  • @adiga you should use a return in arrow functions when you have more business logic that you need to evaluate. If all your doing is immediately returning something then you can use the shorthand return method. – ehutchllew Feb 10 '19 at 11:48

1 Answers1

2

ES6 arrows use implicit return syntax that allows to skip return keyword. This is implicitly returned object:

this.setState(prevState => ({
  ...prevState,
  doggo: someImg.message
}))

Which is a shortcut for explicit return:

this.setState(prevState => {
 return {
  ...prevState,
  doggo: someImg.message
 }
})

This is object literal that is returned as new state:

{
  ...prevState,
  doggo: someImg.message
}

Not wrapping it with (...) parentheses would result in syntax error because {...} curly braces in object literal would be parsed as function brackets.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • Thanks a lot...That really helps...Just a quick question...What does ...prevState represent ? Does it represent the ES6 REST/Spread operator syntax ? – copenndthagen Feb 10 '19 at 16:17
  • This is ES2018 object spread, makes a shallow copy of `prevState` object. It's syntax sugar for `Object.assign({}, prevState)` – Estus Flask Feb 10 '19 at 16:29