Currently experimenting with ngrx store and manipulating elements within an array, such as deleting, fetching, and editing, works smoothly. However, a challenge arises when inserting an object into the array for the first time, duplicating the entry unless filtered in the reducer as seen below.
State
export const initialShoppingState: ShoppingState = {
shoppingList: [],
};
The following implementation works but perhaps filtering should not be necessary to avoid adding duplicate objects.
on(ShoppingAction.shoppingItemAdded, (state, { shoppingItem }) => {
console.log(state);
return ({ ...state, shoppingList: [...state.shoppingList.filter((item) => item.id !== shoppingItem.id), shoppingItem] });
}),
This approach results in the first item being added twice, while subsequent items are only added once.
on(ShoppingAction.shoppingItemAdded, (state, { shoppingItem }) => {
console.log(state);
return ({ ...state, shoppingList: [...state.shoppingList.concat(shoppingItem)] });
}),