Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 / NGRX Combine Reducers

I am using Angular 6 w/ NgRX 4. I have multiple reducers I would like to combine.

app.module.ts

  import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';

    import { StoreModule } from '@ngrx/store';
    import { EffectsModule } from '@ngrx/effects';

    import { StoreDevtoolsModule } from '@ngrx/store-devtools';

    import { AppComponent } from './app.component';
    import counterEffects from './store/counter/counter.effects';

    import reducers from './store/reducers';

    @NgModule({
      declarations: [AppComponent],
      imports: [
        BrowserModule,
        StoreModule.forRoot(reducers),
        EffectsModule.forRoot([counterEffects]),
        StoreDevtoolsModule.instrument({
          maxAge: 10,
        }),
      ],
      providers: [],
      bootstrap: [AppComponent],
    })
    export class AppModule {}

reducers.ts

import { combineReducers } from '@ngrx/store';
import { reducer as counterReducer, key as counterKey } from './counter';
import { reducer as profileReducer, key as profileKey } from './profile';

const appReducer = combineReducers({
  [counterKey]: counterReducer,
  [profileKey]: profileReducer,
});

export default (state, action) => {
  if (action.type === 'REDIRECT_TO_EXTERNAL') {
    state = undefined;
  }

  return appReducer(state, action);
};

My reducers are standard reducers, nothing special there.

Coming from a React / Redux background, I would set multiple reducers up like this, however in Angular when I attempt to select from the store I get undefined. When I attempt to view the store using the dev tools, I can see none of my reducers and state is simply {}

How do I setup multiple reducers in Angular 6 / NgRX 4?

like image 329
Harry Blue Avatar asked Jun 11 '18 18:06

Harry Blue


People also ask

Why do we combine reducers?

This function helps you organize your reducers to manage their own slices of state, similar to how you would have different Flux Stores to manage different state. With Redux, there is just one store, but combineReducers helps you keep the same logical division between reducers.

Can we have multiple stores in NGRX?

The objective of this article is to provide a technical implementation of the NGRX for an application with a complexity that could benefit from adding feature store(s) in addition to the root store.


1 Answers

import { ActionReducerMap } from '@ngrx/store';
import { reducer as counterReducer, key as counterKey } from './counter';
import { reducer as profileReducer, key as profileKey } from './profile';

export interface IAppState {
  [counterKey]: any;
  [profileKey]: any;
}

export const reducers: ActionReducerMap<IAppState> = {
  [counterKey]: counterReducer,
  [profileKey]: profileReducer,
};
like image 117
Harry Blue Avatar answered Oct 17 '22 18:10

Harry Blue