Search code examples
angularngrxngrx-entity

Is it possible to unite Reducer's ActionCreators?


I was thinking of joining some "on()" which do exactly the same thing, thus saving lines of code, is this possible?

Giving an example of my code:

const peopleReducer = createReducer(
    INIT_STATE,
    on(fromPeopleAction.GET_ALL_SUCCESS, (state, { peoples }) => adapter.addMany(peoples, { ...state, loading: false })),
    on(fromPeopleAction.GET_ALL_FAIL, (state, { error }) => ({ ...state, error, loading: false })),
    on(fromPeopleAction.CREATE_SUCCESS, (state, { people }) => adapter.addOne(people, { ...state, loading: false })),
    on(fromPeopleAction.CREATE_FAIL, (state, { error }) => ({ ...state, error, loading: false })),
    on(fromPeopleAction.DELETE_SUCCESS, (state, { id }) => adapter.removeOne(id, { ...state, loading: false })),
    on(fromPeopleAction.DELETE_FAIL, (state, { error }) => ({ ...state, error, loading: false }))
);

Note that we have some "on()" which do the same thing, is it possible to call multiple actions for the same on()?


Solution

  • Judging by on's overloads, I think you can use the same logic for multiple actions if you do this:

    on(action1, action2, action3, ...action10, (state, action) => {})
    

    Note that after 10 actions, you'll lose the types.

    It's also important to notice that the last argument should be the reducer.