Search code examples
angularngrxngrx-effects

NgRx - optionally return either one OR two actions from an effect


I have an effect, where depending on what comes back in the data, I may wish to submit an extra action.

Using information from this post, I can return two actions via the following...

public getData$ = createEffect(() => this.actions$.pipe(
    ofType(myDataActions.getData),
    map(() => this.isPollingActive = true),
    mergeMap(() =>
      this.myService.getAllData()
        .pipe(
          tap(data => this.previousResultsTimeUtc = data.previousResultsTimeUtc),
          mergeMap(data => [
            currentDayActions.getCurrentShiftSuccess(data.currentDay),
            myDataActions.getDataSuccess(data)
          ]),
            catchError(err => of(myDataActions.getDataFail(err)))
          ))
    ));

However, ideally, I would sometimes just want to submit a single actions,

eg

    ...
      mergeMap(data => [
            if (data.currentDay !== undefined) // <-- how to do this
              currentDayActions.getCurrentDaySuccess(data.currentDay),

            myDataActions.getDataSuccess(data.data)
          ]),

So, I only want to submit the currentDayActions.getCurrentDaySuccess if I get the data.

Of course the above is incorrect syntax, but I cant quite see how to get this "if" inside of here.

Update

Very similar example of this is here

The effect trying to do the same thing is in feature1/state/feature1.effects.ts


Solution

  • An if else statement would do the trick:

    public continuePolling$ = createEffect(() =>
        this.actions$.pipe(
          ofType(
            feature1Actions.startPollSuccess,
    
            takeWhile(() => this.isPollingActive),
            mergeMap(() =>
              this.feature1Service.getData().pipe(
                delay(8000),
                tap(
                  data =>
                    (this.previousResultsTimeUtc = data.previousResultsTimeUtc)
                ),
                switchMap(data => {
                  if (data.currentDay == undefined) {
                    return [feature1Actions.getLibrarySuccess(data)];
                  } else {
                    return [
                      feature1Actions.getCurrentDaySuccess(data.currentDay),
                      feature1Actions.getLibrarySuccess(data)
                    ];
                  }
                }),
                catchError(err => of(feature1Actions.getLibraryFail(err)))
              )
            )
          )
        )
      );