How to add a new object to a nested object in reducer ? I have this object the current behavior is a new action simply overrides, the previous action but my goal is to add that array at the end ? and please any general guidelines how to simply deal with the state ? I know the following the state is immutable thus it has to be copied using the spread operator , as you can see in the code I did copy twice still there must by another copy missing but I have no clue where I experimented but no positive. if I add ...(state.item[action.grandParentId] ?? []), under [action.grandParentId] I get really close but it copies the targeted object instead of updating.
//initial state
items : {}
// State Action
const AddItem = (select, id, idparent, grandParentId, index) => {
dispatch({
type: ADD_ITEM,
ITEM: select.item,
id: id,
idparent: idparent,
grandParentId: grandParentId,
index: index,
});
};
// ADD ITEM
case ADD_ITEM:
return {
...state,
Items: {
...state.Items,
[action.grandParentId]: [
...(state.exercises[action.grandParentId] ?? []),
{
[action.idparent]: [
...(state.Items[action.idparent] ?? []),
{
index: action.index,
id: action.id,
item: action.item,
},
],
},
],
},
};
From what I can tell you need to also shallow copy the "grandparent", but in this case since you are updating an exiting element of intermediate state you need to map the array to a new array, replacing the element with the matching id.
// ADD ITEM
case ADD_ITEM:
return {
...state,
Items: {
...state.Items,
[action.grandParentId]: (state.Items[action.grandParentId] ?? []).map(
item => item[action.idparent]
? {
...item,
[action.idparent]: [
...(item[action.idparent] ?? []),
{
index: action.index,
id: action.id,
item: action.item,
},
],
}
: item
),
},
};