I have an array of objects currently in my store. I want to update a single property of that object given a passed in object.
State
export interface ApplicationState {
...
allNavGroups: INavGroup[] | null;
}
Reducer
on(ApplicationActions.toggleCollapseNavGroup, (state, group: INavGroup ) => {
const navGroup = state.allNavGroups.find( g => g.groupId === group.groupId);
navGroup.collapsed = !navGroup.collapsed;
return { ...state };
})
However, this results in:
ERROR TypeError: Cannot add property collapsed, object is not extensible
After seeing this GitHub issue, I tried doing it this way instead, but same issue:
const navGroups = [ ...state.allNavGroups ];
const navGroup = navGroups.find( g => g.groupId === group.groupId);
navGroup.collapsed = !navGroup.collapsed;
return { ...state, allNavGroups: navGroups };
I have seen a few threads on different ways to update an object in an array, but it seems like a lot of code to do a simple thing. In other threads, I saw that you have to replace the object, not update it. When I tried that, it seemed to work. However, that requires more logic to be added to make sure the order of the array is the same as it once was.
Is there a simple way to update just a property on an object within an array of objects that is in the Store
?
Update If I iterate through each object in the array and destructure it, it works. This seems like a hack.
const navGroups = state.allNavGroups.map(g => ({ ...g }));
const navGroup = navGroups.find( g => g.groupId === group.groupId);
navGroup.collapsed = !navGroup.collapsed;
return { ...state, allNavGroups: navGroups };