1
votes

I am having some trouble understanding why I am getting an error message:

TypeError: Cannot assign to read only property 'description' of object '#'

I know that the principle is that I don't want to modify state in my reducer. Instead, I want to return a new copy of the state.

Here is my reducer:

action TOGGLE_CHECKBOX:
    {
        let copyOfItems = [...state.items]; // create a new array of items

        copyOfItems.forEach(i => i.description = "newDescription");

        // return a new copy of the state
        return {
            ...state,
            items: copyOfItems
        }
    }

And here is my Reducer test:

it ('Test that each item description is set', () => {
    const state = {
        items: [
            { description: "d1" },
            { description: "d2" }
        ]
    }

    deepFreeze(state);

    expect(MyReducer(state, { type: TOGGLE_CHECKBOX })).toEqual({
        items: [
            { description: "newDescription" },
            { description: "newDescription" }
        ]
    });
});

However, I get the above error message. If I remove the deepFreeze the test passes. This means that I am somehow modifying the original state in some way but I can't figure out why especially because I created a new array of spreaded items.

Any help would be greatly appreciated.

2

2 Answers

7
votes

The array spread operator makes a shallow copy of the state.items array, but does not make a copy of the objects inside of that array. In order to get a new array with modified items you can map over state.items and use the object spread operator to update the items:

action TOGGLE_CHECKBOX:
    {
        const copyOfItems = state.items.map(
          i => ({...i, description: 'newDescription'})
        ); // create a new array of items with updated descriptions

        // return a new copy of the state
        return {
            ...state,
            items: copyOfItems
        }
    }
0
votes

The spread operator makes shallow copy of the array which means the object inside the array will still hold the reference to the original values. You need to make a new copy for each object and then update the description for each like this

let copyOfItems = state.items.map( obj => ({
  ...obj,
  description: "newDescription"
})); 

return {
  ...state,
  items: copyOfItems
}

Hope this helps !