Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
183
rated 0 times [  189] [ 6]  / answers: 1 / hits: 30449  / 5 Years ago, thu, september 5, 2019, 12:00:00

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.


More From » reactjs

 Answers
16

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
}
}

[#51686] Thursday, August 29, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trevionbronsonr

Total Points: 160
Total Questions: 85
Total Answers: 110

Location: Bonaire
Member since Wed, Mar 29, 2023
1 Year ago
trevionbronsonr questions
;