23

I have a simple situation, I have actions Like CreatUser, CreateSuccess, CreateFail. How should I add new object to array and when Create action is dispatched or CreateSuccess? And how should I do that?

export function reducer(state = init, action: Actions): State {
switch (action.type) {
    case ActionsTypes.CREATE:
        return {
            ...state,
            inProgress: true
        };
    case ActionsTypes.CREATE_SUCCESS:
        return {
            ...state,
            users: state.users.push(action.payload),
            inProgress: false
        };
    case ActionsTypes.CREATE_FAIL:
        return {
            ...state,
            error: action.payload,
            inProgress: false
        };
    default:
        return state;
}

In code above I tried to add new user using push method, but it is not good solution. How should I do that?

Adam Adamski
  • 737
  • 3
  • 11
  • 20

4 Answers4

39

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.

Kliment Ru
  • 2,057
  • 13
  • 16
9

Your state should be immutable therefore would be better to use

users: state.users.concat(action.payload)
Igor Litvinovich
  • 2,436
  • 15
  • 23
6

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]

sai amar
  • 1,758
  • 1
  • 10
  • 9
  • that would be a bad idea for big arrays... this spread creates new array and copies the data into it.. – Deian Apr 30 '21 at 18:33
6
export const reducer = createReducer(initialState,
  on(addTodo, (state, { todo }) => ({
    ...state,
    todoInput: '',
    todos: [...state.todos, todo]
  }))
);

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

RobC
  • 22,977
  • 20
  • 73
  • 80