Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stuck in endless loop when not dispatching an action in ngrx/effects

Tags:

angular

ngrx

I'm using Angular2 and ngrx/store and ngrx/effects for state management.

When a certain action fails I want to show an error message but it seems that I can't perform this task in an @Effects() block. See the following:

  @Effect() selectOfficeFail$ = this.actions$
   .ofType(SelectOfficeActions.LOAD_FAIL)
   .do(() => {
     alert('Error! No offices found!'); // I keep entering here
  });

When the code above runs the alert is run endless number of times until the browser crashes. It seems an @Effect() has to return a new dispatch() but I don't understand why. And why does the alert() above run endless number of times?

Edit: I am not dispatching SelectOfficeActions.LOAD_FAIL multiple times. Only once

like image 779
Weblurk Avatar asked Aug 25 '16 11:08

Weblurk


2 Answers

if using createEffect function then the dispatch: false flag needs to be passed as config parameter (ngrx.io reference)

effectName$ = createEffect(
  () => this.actions$.pipe(
    ofType(FeatureActions.actionOne),
    tap(() => console.log('Action One Dispatched'))
  ),
  { dispatch: false }
  // FeatureActions.actionOne is not dispatched
);
like image 119
Alex Nazarevych Avatar answered Sep 21 '22 15:09

Alex Nazarevych


[UPDATE] Now the best way to do that is to use dispatch option like this:

@Effect({dispatch: false}) selectOfficeFail$ = this.actions$
    .ofType(SelectOfficeActions.LOAD_FAIL)
    .do(() => {
        alert('Error! No offices found!'); // I keep entering here
    });

It means "reacts to this action but don't send another".

like image 29
bertrandg Avatar answered Sep 20 '22 15:09

bertrandg