Search code examples
angularngrxngrx-store

ngrx - Nesting reducers


I am trying to implement a "workspace" feature into an Angular ngrx 4 webapp that allows the user to have multiple states of the same app which he can switch between through ui elements on the screen. How would I implement this on my reducer state?

Currently my rootReducer looks like this:

export const reducers: ActionReducerMap<State> = {
   layout: fromLayout.layoutReducer,
   properties: fromProperties.propertiesReducer,
   grid: fromGrid.gridReducer
}

Now I would like to nest these so I can change the whole state by switching workspaces.

Say I would like to switch a workspace I can not add this workspaceReducer in any of the current reducers. It would have to be a parent to the current ActionReducerMap (at least I think so).

What is the best practice to implement something like this in ngrx. T


Solution

  • You can probably use a meta-reducer:

    export const SWITCH_WORKSPACE = 'SWITCH_WORKSPACE';
    
    export function switchWorkspace( reducer ) {
      return function newReducer( state, action ) {
    
        if ( action.type === SWITCH_WORKSPACE ) {
          state = getWorkspaceState(action.workspace);
        }
    
        const nextState = reducer(state, action);
    
        return nextState;
    
      }
    }
    

    And in your app module:

    StoreModule.forRoot(reducers, { 
        metaReducers: [switchWorkspace]
    }),
    

    For more info on meta-reducers, see https://netbasal.com/implementing-a-meta-reducer-in-ngrx-store-4379d7e1020a