Home > Software design >  What is the difference between using spread operator in brackets and without
What is the difference between using spread operator in brackets and without

Time:09-07

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?

CodePudding user response:

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.

CodePudding user response:

From the docs:

Keep in mind that returning object literals using the concise body syntax (params) => {object:literal} will not work as expected.

This is because the code inside braces ({}) is parsed as a sequence of statements (i.e. foo is treated like a label, not a key in an object literal).

You must wrap the object literal in parentheses:

CodePudding user response:

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

is equivalent to the following statement

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