Search code examples
angularrxjsngrxngrx-effects

ngrx effect throws "dispatched an invalid action: undefined"


I have this effect for logout confirmation under the condition of a dialog response, but am getting the following errors:

ERROR Error: Effect "AuthEffects.logoutConfirmation$" dispatched an invalid action: undefined

and

ERROR TypeError: Actions must be objects

heres the effect:

@Effect()
logoutConfirmation$ = this.actions$
    .ofType<Logout>(AuthActionTypes.Logout)
    .pipe(
      map(action => {
        if (action.confirmationDialog) {
          this.dialogService
            .open(LogoutPromptComponent)
            .afterClosed()
            .pipe(
              map(confirmed => {
                if (confirmed) {
                  return new LogoutConfirmed();
                } else {
                  return new LogoutCancelled();
                }
              })
            );
        } else {
          return new LogoutConfirmed();
        }
      })
    );

it works when confirmation dialog is activated, I guess it's something wrong with the map of the dialog's response, have been trying to understand it but couldn't fin a way. Any one has a clue on this?


Solution

  • Your outer map should be a mergeMap, as you are mapping the action to a new stream (in case that the condition is true).

    You can fix this as follows:

    import { of } from 'rxjs';
    import {map, mergeMap } from 'rxjs/operators';
    
    @Effect()
    logoutConfirmation$: Observable<Action> = this.actions$
        .ofType<Logout>(AuthActionTypes.Logout)
        .pipe(
          mergeMap(action => {
            if (action.confirmationDialog) {
              return this.dialogService
                .open(LogoutPromptComponent)
                .afterClosed()
                .pipe(
                  map(confirmed => confirmed ? new LogoutConfirmed():new LogoutCancelled())
                );
            } else {
              return of(new LogoutConfirmed());
            }
          })
        );
    

    As a side note, always declare the explicit type of your effects in order to get errors at compile instead of run time.