javascriptreactjsreduxjavascript-objectsobject-property

cannot assign to read-only property of object


#interestingProblem can anybody explain, please 🤔 I had a problem while updating the state as in the first code block, but there was no problem when I updated the state as in the second code block as below.

I had a problem: (cannot assign to read-only property of object quantity)

const newItem = action.payload
newItem.quantity = 1
state.items = [...state.items, newItem]

I had no problem when I wrote the code like this

const newItem = action.payload
state.items = [...state.items, { ...newItem, quantity: 1 }]

Solution

  • 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]