I'm looking to add a new item object to a category in a reducer. The reducer receives a category index and a new item object.
Does anyone know the best way to update the state immutably with this data structure:
const initialState = {
categories: [
{
id: 1,
name: "vegetables",
items: [
{name: "potatoes", id: Math.floor(Math.random() * 99999)},
{name: "carrots", id: Math.floor(Math.random() * 99999)}
]
},
{
id: 2,
name: "dairy",
items: [
{name: "milk", id: Math.floor(Math.random() * 99999)},
{name: "cheese", id: Math.floor(Math.random() * 99999)}
]
},
{
id: 3,
name: "meat",
items: [
{name: "chicken", id: Math.floor(Math.random() * 99999)}
]
}
]
}
Or is it best to use an external package, such as immutable.js?
There are many other similar questions on stackoverflow but none that have the same structure.
Update
The rest of the reducer looks like:
const shoppingItemsReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_SHOPPING_ITEM:
const categories = [...state.categories];
categories[action.selectedCategoryIndex].items.push(action.newItemObj);
return {
...state,
categories
}
default:
return state
}
}
Using push
works fine but it's mutating the state