How to dispatch an empty action?

Hongbo Miao picture Hongbo Miao · Sep 29, 2016 · Viewed 10.8k times · Source

I am using ngrx/effects.

How can I dispatch an empty action?

This is how I am doing now:

 @Effect() foo$ = this.actions$
    .ofType(Actions.FOO)
    .withLatestFrom(this.store, (action, state) => ({ action, state }))
    .map(({ action, state }) => {
      if (state.foo.isCool) {
        return { type: Actions.BAR };
      } else {
        return { type: 'NOT_EXIST' };
      }
    });

Since I have to return an action, I am using return { type: 'NOT_EXIST' };.

Is there a better way to do this?

Answer

cartant picture cartant · Sep 29, 2016

I've used similar unknown actions, but usually in the context of unit tests for reducers.

If you are uneasy about doing the same in an effect, you could conditionally emit an action using mergeMap, Observable.of() and Observable.empty() instead:

@Effect() foo$ = this.actions$
  .ofType(ChatActions.FOO)
  .withLatestFrom(this.store, (action, state) => ({ action, state }))
  .mergeMap(({ action, state }) => {
    if (state.foo.isCool) {
      return Observable.of({ type: Actions.BAR });
    } else {
      return Observable.empty();
    }
  });