Search code examples
javascriptangulartypescriptredux

Angular update an object in an array with new values, inside a reducer


Basically, I have an array of categories objects, where an object looks like this {"categoryId":10, "categoryName":"beverages", "description": "drinkable liquids"} and after I modify the information in any of the last two attributes of the category, I want to be able update the data.

My code is:

const reducer = createReducer(
initialCategoriesState,
on(categoriesActions.updateCategory, (state, {data }) => ({
...state
categories: state.categories?.map((item) => (item['categoryId'] === data['categoryId'] ? data:item)),
}))

But it doesn't update the category that I want, it just creates a new category with the new details that were supposed to belong to the category that I must be updated


Solution

  • You can use object spread syntax to combine two objects:

    state.categories?.map(item => item.categoryId === data.categoryId ? {...item, ...data} : item)