0

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?

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
Karol Trzaska
  • 47
  • 1
  • 5
  • Does this answer your question? [Arrow function without curly braces](https://stackoverflow.com/questions/39629962/arrow-function-without-curly-braces) – Wing Sep 07 '22 at 10:43
  • when you add parenthesis () means returning function data from a single line without writing return statement. – Arman Sep 07 '22 at 10:43
  • The first one doesn't actually return anything. The second one however is shorthand for `setSomeValue(oldValue => { return {...oldValue, someField: 'newValue'}; })` – Nsevens Sep 07 '22 at 10:44

2 Answers2

2

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.

Rajesh
  • 24,354
  • 5
  • 48
  • 79
1
setSomeValue(oldValue => ({...oldValue, someField: 'newValue'}))

is equivalent to the following statement

setSomeValue(oldValue => {
    return {...oldValue, someField: 'newValue'};
})
Arman
  • 641
  • 4
  • 12