score:2

Accepted answer

the first approach you are mutating action.payload directly since you are not creating a copy to newitem but passing the same reference. given action.payload is readonly you face the error:

// passing the same reference, 'newitem' points to 'action.payload'
// hence newitem is not copy
const newitem = action.payload
// here you mutate 'action.payload' since 'newitem' points to same reference
newitem.quantity = 1
state.items = [...state.items, newitem]

second approach works because you are creating a copy from action.payload not mutating it:

// here 'newitem' still points to same reference 'action.payload'
const newitem = action.payload
// but here you are spreading the values into a new object, not mutating directly
state.items = [...state.items, { ...newitem, quantity: 1 }]

instead you should create a copy first to your approach to work:

// here you create a new object from 'action.payload''action.payload'
// hence newitem contains the same values but it's a different object
const newitem = { ...action.payload }
// now you are not mutating 'action.payload', only 'newitem' that's a new object
newitem.quantity = 1
state.items = [...state.items, newitem]

score:0

because when doing a like **kwargs with state in react i assume, you are passing a no nested state into one that has a nested state reassinging it to a non-nested stated breaking the goal of you're code.

score:1

action.payload might be a readonly object. on the second code block, the spread operator passes the key-value pairs to the new object.


Related Query

More Query from same tag