Search code examples
javascriptangulartypescriptreduxngrx

With NgRx, what is the correct way to reset, or return an empty array inside of the state object?


What would be the correct way to return an empty array in an NgRx reducer?

I use NgRx to write a basic reducer which includes an empty array, myArray in my initial state:

import * as MyActions from './my.actions';
const myState = {
    myValue: 'foo',
    myArray: []
}

And, I have an action ARRAY_RESET which returns myArray as an empty array as follows:

export function myReducer(
    state = myState,
    action: MyActions.MyActionTypes
) {
    switch(action.type) {
        case MyActions.ARRAY_RESET:
            return {
                ...state,
                myArray: []   <---- I RETURN AN EMPTY ARRAY
            };
        case MyActions.ARRAY_PUSH:
            return {
                ...state,
                myArray: [...state.myArray, action.payload]
            };
        default:
            return state;
    }
}

Is this the correct approach?


Solution

  • Yes, to reset it, or empty it, we should just set it as a new, empty array:

    return {
      ...state,
      myArray: []   <---- RETURN AN EMPTY ARRAY
    };