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

The problem is that do allows the action to flow through your effect and the action is then dispatched, again, by the store. You could use filter to prevent that from happening:

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

Yes you're right the @effect needs to dispatch a new action, but i think there is something wrong in your application logic.

You shouldn't be dispatching the SelectOfficeActions.LOAD_FAIL action in a component or service but rather a a LOAD action which invokes an @Effect and the effect in turn dispatches a LOAD_COMPLETE or LOAD_FAIL based on the criteria.

Something like this example from the libraries github

 @Effect() login$ = this.updates$
      // Listen for the 'LOGIN' action
      .whenAction('LOGIN')
      // Map the payload into JSON to use as the request body
      .map(update => JSON.stringify(update.action.payload))
      .switchMap(payload => this.http.post('/auth', payload)
        // If successful, dispatch success action with result
        .map(res => ({ type: 'LOGIN_SUCCESS', payload: res.json() }))
        // If request fails, dispatch failed action
        .catch(() => Observable.of({ type: 'LOGIN_FAILED' }));
      );

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
);

[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".

Tags:

Angular

Ngrx