Search code examples
angularrxjsngrx

infinite loop in effect


EDIT I have the following =>

  @Effect()
  createMission$ = this.actions$.pipe(
    ofType<featureActions.CreateMissionRequest>(featureActions.ActionTypes.CreateMissionRequest),
    switchMap((action) =>
        this.store$.pipe(select(MissionsStoreSelectors.getById(), {id : action.payload.routeId}))),
    switchMap((mission) => this.dataService.createMission(this.APIMissionFromMissionRoute(mission)).pipe(
        map(response => new featureActions.CreateMissionSuccess({response, mission})),
        catchError((error: HttpErrorResponse) => {
          return of(new featureActions.CreateMissionFailed({error}));
        }),
      )
    )
  );

right now, there is no server, but I faked the reply with an observable

  createMission(params: API_MODEL.IMissionAPI): Observable<API_MODEL.CreateMissionResponse> {
    return new Observable(observer => {
      setTimeout(() => {
        observer.next({
            result: {
                status: 2
            },
            missionID: {
                identifier: 41
            }
        });
        observer.complete();
      }, 120);
    });
  }

the thing is, my second switchmap switchMap((mission) => this.dataService.createMission(this.APIMissionFromMissionRoute(mission)) is looping. this is because my first switchMap is getting a selectore with a parameter, and when my state is updated, it trigger again my second switchmap.

I would like to know if there is a way to get my current state in another way.

I tried withLatest, but I need to access the current action.payload to get what I want, and I can't pass action to withLatest


Solution

  • You should use take operator to let outer observable complete like this [otherwise as you said that store will get updated and it will trigger to execute the selector] -

    this.store$.pipe(select(MissionsStoreSelectors.getById(), {id : action.payload.routeId})).pipe(take(1)))