'NGRX REDUCERs using SAME STATE object

I will reformulate the question:

Got these two reducers:

export function reducer1(state: State = initialState,: Actions1.Actions1);
export function reducer2(state: State = initialState,: Actions2.Actions1);

I need those reducers to modify the same state object.

As they will use the same state object, I cannot simply split the state into small pieces to those new reducers use them as this answer says => https://stackoverflow.com/a/51970052/2992476

Thanks in advance



Solution 1:[1]

At first part you already mention that spliting reducer to small reducer so I would not mention again.

Secondly you can use NGRX/Entity to let NGRX handle CRUD operation for you so the code complexity would be reduce because NGRX/Entity already include some API allow developer to do CRUD operation on the state.

Example:

const userReducer = createReducer(
  initialState,
  on(UserActions.addUser, (state, { user }) => {
    return adapter.addOne(user, state)
  }),
  on(UserActions.upsertUser, (state, { user }) => {
    return adapter.upsertOne(user, state);
  }),
  on(UserActions.addUsers, (state, { users }) => {
    return adapter.addMany(users, state);
  }),
  on(UserActions.upsertUsers, (state, { users }) => {
    return adapter.upsertUsers(users, state);
  }),
  on(UserActions.updateUser, (state, { user }) => {
    return adapter.updateOne(user, state);
  }),
  on(UserActions.updateUsers, (state, { users }) => {
    return adapter.updateMany(users, state);
  }),
  on(UserActions.mapUsers, (state, { entityMap }) => {
    return adapter.map(entityMap, state);
  }),
  on(UserActions.deleteUser, (state, { id }) => {
    return adapter.removeOne(id, state);
  }),
  on(UserActions.deleteUsers, (state, { ids }) => {
    return adapter.removeMany(ids, state);
  }),
  on(UserActions.deleteUsersByPredicate, (state, { predicate }) => {
    return adapter.removeMany(predicate, state);
  }),
  on(UserActions.loadUsers, (state, { users }) => {
    return adapter.addAll(users, state);
  }),
  on(UserActions.clearUsers, state => {
    return adapter.removeAll({ ...state, selectedUserId: null });
  })
);

Solution 2:[2]

This solution Splitting big reducer into smaller reducers is not exactly to your question in grabbing the same state object.

here my solution that might be solvable:

export const mergeReducers = <TState>(...reducers: ActionReducer<TState>[]): ActionReducer<TState> => {
  return (state: TState, action: Action) => {
    if (reducers.length === 0) {
      throw new Error('At least one reducer is required');
    }

    return reducers.reduce((initialState, reducer) => {
      return reducer(initialState, action);
    }, state);
  };
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tony Ngo
Solution 2 MilV