Reputation: 50752
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.
Upvotes: 1
Views: 333
Reputation: 222498
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.
Upvotes: 2