Ilya Loskutov
Ilya Loskutov

Reputation: 2201

ngrx: initial action fired twice for reducers

//first.reducer.ts
export function firstReducer(state: number = 0, action: actions.actionsForFirst): number{
    console.log("firstReducer")
    console.log(action)
    switch(action.type) {
        ...
        return state;
    }        
}

//second.reducer.ts
export function secondReducer(state: string = "qwe", action: actions.actionsForSecond): string {
    console.log("secondReducer")
    console.log(action)
    switch(action.type) {
        ...
        return state;
    }        
}

 //store.module.ts
    const reducers = {  firstReducer, secondReducer };
    @NgModule({
        imports: [
            StoreModule.provideStore(reducers), //import reducers
        ],
        ...
    })
    export class StoreModule { };

//app.module.ts
import { StoreModule } from '@ngrx/store';
import { CoreStoreModule } from './core-store.module'; // module with reducers
@NgModule({
    bootstrap: [AppComponent],
    imports: [
        CoreStoreModule,
        effects.map(effect => EffectsModule.run(effect)) //register some imported effects
    ],
    ...
})
export class AppModule { }

Log output:

firstReducer Object type: "@ngrx/store/init"proto: Object

secondReducer Object type: "@ngrx/store/init"proto: Object

firstReducer Object type: "@ngrx/store/init"proto: Object

secondReducer Object type: "@ngrx/store/init"proto: Object

i.e. @ngrx/store/init action was fired twice for both firstReducer and secondReducer.

What can it be the reason of this behavior? There is the open issue for it

Upvotes: 0

Views: 1898

Answers (1)

Mavlarn
Mavlarn

Reputation: 3883

In store module, you init the store with StoreModule.provideStore(reducers). Then you in main module imported the store module. It make it init twice. you should add StoreModule.provideStore(reducers) only in main module.

Upvotes: 3

Related Questions