Home > Software design >  Grouping the state with NgRx is not working
Grouping the state with NgRx is not working

Time:09-16

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
    })
        
      ]

CodePudding user response:

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,
});

CodePudding user response:

Using the combineReducers I achieved that

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