Jalaleddin Hosseini
Jalaleddin Hosseini

Reputation: 2272

Service is called multiple times inside NgRx Effect

When I dispatch an action, service is called more than one time inside effect and I have to use "exhaustMap" instead of "concatMap" or "mergeMap" in all effects every time, and I do not know how it happened suddenly because it was OK before. And I know that I do not dispatch one action before one time but it calls the service more than one time (in this case two times).

I imported effect in contact module like this:

EffectsModule.forFeature([PersonalContactEffects]),
StoreModule.forFeature(personalContactFeatureKey, personalContactReducer)

and the Effect is:

        loadPersonalContacts$ = createEffect(
        () => this.actions$.pipe(
            ofType(personalContactActions.loadPersonalContactsList),
            tap(action => console.log("before service call", action)),
            concatMap(action => this.contactService.getList(action.query)),
            map(personalContactList => personalContactActions.personalContactsListLoaded({ personalContactList })),
            catchError(() => of(personalContactActions.setLoading({ loading: false })))
        )
    );

and I dispatch this action like this:

this.store.dispatch(fromPersonalContactActions.loadPersonalContactsList({ query }));

enter image description here

enter image description here

Beside above issue, I've got noticed that every Reducer is called twice every time an action is dispatched. And all these issues happen from the time when I imported "StoreModule.forFeature" to other lazy loaded modules.

Upvotes: 2

Views: 1414

Answers (2)

Sandeep K Nair
Sandeep K Nair

Reputation: 2932

For me the issue was with defining

private state: State<AppState> instead of private state: Store<AppState> when using the following configuration


// Configure global states
const globalStates = [
  provideState(authFeatureKey, authReducer),
  // Register additional states here
];

export const appConfig: ApplicationConfig = {
  providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(AppRoutes),
    // NGRX Configuration
    provideStore(),
    ...globalStates,
    provideEffects(globalEffects),
    // Only for development
    provideStoreDevtools({
      maxAge: 25,
      logOnly: false,
    }),
  ],
};

Angular: 18 and Ngrx: 18

Upvotes: 0

Jalaleddin Hosseini
Jalaleddin Hosseini

Reputation: 2272

Finally I could find the answer, and this is because of

StoreDevtoolsModule.instrument({...})

in appModule, and I commented it, so it does not call services twice inside effects and also does not call reducers twice. As mentioned in below links in github:

https://github.com/ngrx/platform/issues/1054

https://github.com/ngrx/platform/issues/1325

Upvotes: 1

Related Questions