Search code examples
reduxngrx

Dispatch an action after another is executed in Effect


I Have the following function in my code

    private loadDrones() {
    this.store$.dispatch(new UsedDronesStoreActions.GetUsedDronesRequest({organizations_id : environment.organizationId}));
    this.store$.pipe(select(UsedDronesStoreSelectors.selectAll)).subscribe((drones) => {
      drones.forEach((drone) => {
        if (this.drones.has(drone.id)) { return; }
        this.drones.set(drone.id, drone);
        this.store$.dispatch(new UsedDronesStoreActions.OpenUsedDroneUpdatePositionChannelRequest({ droneId: drone.id, projectId : environment.projectId }));
        this.store$.dispatch(new UsedDronesStoreActions.OpenUsedDroneUpdateStatusChannelRequest({ droneId: drone.id, projectId : environment.projectId }));
      });
    });
  }

I would like to move this function into an INIT Action in my effect.

Using

  @Effect()
  init$ = this.actions$.pipe(
    ofType(ROOT_EFFECTS_INIT),
    map(action => ...)
  );

My question is, , the actual function load a list, and then thank to the result of that list, dispatch a serie of actions for each element of the list.

Is it possible to make this inside a single effect ? Or do I have to split it up in 2 different actions ?


Solution

  • https://medium.com/@amcdnl/dispatching-multiple-actions-from-ngrx-effects-c1447ceb6b22

    @Effect() save = this.update$.pipe(
       map(action => action.payload),
       switchMap(payload => this.myService.save(payload)),
       switchMap(res => [
           new Notification('save success'),
           new SaveSuccess(res)
       ])
    );