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

Adam Adamski picture Adam Adamski · Aug 31, 2018 · Viewed 15.2k times · Source

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?

Answer

Kliment Ru picture Kliment Ru · Aug 31, 2018

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.