Search code examples
javascriptangulartypescriptngrx

Grouping the state with NgRx is not working


I am trying to group the state.

Index.ts

export const reducers: ActionReducerMap<ApplicationState> = {
  admin: adminReducer
};

export const metaReducers: MetaReducer<ApplicationState>[] = [];

Admin Reducer

export const adminReducer: any = {
    productCategory: ProductCategoryReducer,
    productVendor: ProductVendorReducer,
    productSubCategory: ProductSubCategoryReducer,
    products: ProductsReducer,
    product: ProductReducer,
    productDiscount: ProductDiscountReducer
};

When I run the application, on redux tool,I am not able to see the state. It is blank

export interface ApplicationState {
    admin: AdminState
}

export interface AdminState {
    productCategory: ProductCategoryState;
    productVendor: VendorState;
    productSubCategory: ProductSubCategoryState;
    products: ProductsState;
    product: ProductState;
    productDiscount: ProductDiscountState
}

enter image description here

Register

    imports: [
        
        StoreModule.forRoot(reducers, { metaReducers }),
        EffectsModule.forRoot([]),
StoreDevtoolsModule.instrument({
      maxAge: 25
    })
        
      ]

Solution

  • The Reducer is a "function that takes an Action and a State, and returns a State", not an object, so you can't group the reducers to each other just by creating one object containing them.

    Thanks for NgRx combineReducers function, which provides a way to combine multiple states, and returns the combined reducer as a function (with state & action args) that handles the sub-states changes and returns the combined state.

    So you can simply combine the reducers using combineReducers like the following:

    export const adminReducer = combineReducers({
        productCategory: ProductCategoryReducer,
        productVendor: ProductVendorReducer,
        productSubCategory: ProductSubCategoryReducer,
        products: ProductsReducer,
        product: ProductReducer,
        productDiscount: ProductDiscountReducer,
    });