Angular 6 ngrx, how to add new item to array in state object?

依然范特西╮ 提交于 2019-12-05 02:01:22

Try to use the spread operator because it creates a new array of users and does not mutate the previous array.

users: [...state.users, action.payload]

Or else use @ngrx/entity module for arrays. It's the best way.

Update 13.07.2019

New module @ngrx/data is available in NgRx 8. This module helps to create CRUD store for arrays with zero boilerplate.

Your state should be immutable therefore would be better to use

users: state.users.concat(action.payload)

This is for those who is searching how to add item at the begining of the array in an immutable manner unlike using unshift operator which mutates the original. Placing new item at the begining of operation makes the magic

users: [action.payload,...state.users]

Manuel Gonzalez
export const reducer = createReducer(initialState,
  on(addTodo, (state, { todo }) => ({
    ...state,
    todoInput: '',
    todos: [...state.todos, todo]
  }))
);

See: https://ngrx.io/guide/store/configuration/runtime-checks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!