What is the difference between using spread operator in brackets and without

Viewed 51

today I encountered that it is impossible to set state in react native using old state value and then utilizing spread operator like this:

setSomeValue(oldValue => {...oldValue, someField: 'newValue'})

it is necessary to add parentheses:

setSomeValue(oldValue => ({...oldValue, someField: 'newValue'}))

and then everything works just fine.

What is the reason?

2 Answers

You define a block of arrow function using {}. So when you do () => {} you are not returning an object. You are returning nothing.

You can update this code to return an object as:

() => {
    return { someField: 'newValue' }
}

But JS provides a shortcut to use parenthesis () to create a expression and return it.

So, () => () will return any expression inside second (). So when you do () => ({ someField: 'newValue' }), now you are returning an object directly without creating block and doing an implicit return.

setSomeValue(oldValue => ({...oldValue, someField: 'newValue'}))

is equivalent to the following statement

setSomeValue(oldValue => {
    return {...oldValue, someField: 'newValue'};
})
Related