Search code examples
ngrxngrx-store

Console log the state data when using ngrx for State Management in Angular


Can anyone suggest how to console log the state when using ngrx for state management in angular application. I have gone through ngrx-store-logger but the documentation is not clear as how to create meta-reducers and use this library.


Solution

  • This can be done with a meta reducer, as shown in the NgRx example app

    export function logger(reducer: ActionReducer<State>): ActionReducer<State> {
      return (state: State, action: any): any => {
        const result = reducer(state, action);
        console.groupCollapsed(action.type);
        console.log('prev state', state);
        console.log('action', action);
        console.log('next state', result);
        console.groupEnd();
    
        return result;
      };
    }
    
    /**
     * By default, @ngrx/store uses combineReducers with the reducer map to compose
     * the root meta-reducer. To add more meta-reducers, provide an array of meta-reducers
     * that will be composed to form the root meta-reducer.
     */
    export const metaReducers: MetaReducer<State>[] = !environment.production
      ? [logger, storeFreeze]
      : [];
    

    And add it to the module:

    @NgModule({
      imports: [
        StoreModule.forRoot(..., { metaReducers })
      ]
    })