Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NgRx: dispatch multiple actions in a single effect

I need to dispatch multiple actions after calling an API request in my effect. I'm using this code at the moment to dispatch one action after API request done:

 changeStatus$ = createEffect(() => 
  this.actions$.pipe(
    ofType(fromJtDetail.changeStatus),
    switchMap(action =>
      this.jtDetailService.changeStatus(action.entity,action.jobTicketId).pipe(
        map(res => fromJtDetail.statusChanged({changedStatus: action.entity.newStatus})),
        catchError(error => EMPTY)
))));

It's important to dispatch more actions in this effect, can't write another effect for this.

like image 434
Rashed Bayani Avatar asked Sep 12 '25 19:09

Rashed Bayani


2 Answers

You can dispatch multiple actions using switchMap + of(

changeStatus$ = createEffect(() => 
  this.actions$.pipe(
    ofType(fromJtDetail.changeStatus),
    switchMap(action =>
      this.jtDetailService.changeStatus(action.entity,action.jobTicketId).pipe(
      switchMap(res => of(
        fromJtDetail.statusChanged({changedStatus: action.entity.newStatus}),
        fromHere.doSmthAction(),      // <-- additional action 1
        fromThere.doSmthElseAction(), // <-- additional action 2
      )),
      catchError(error => EMPTY)
))));

EDIT:
Althought it can be done you should not do it.
Have a look at no-multiple-actions-in-effects

EDIT2:
The initial link is from a now archived repo. The rule is still correct, it simply got moved to the NgRx core. Check here no-multiple-actions-in-effects

like image 72
Deitsch Avatar answered Sep 14 '25 10:09

Deitsch


All of the answers here are correct, the "simple" answer and solution is to return an array of actions. However, this is a bad-practice, for more info see No Multiple Actions In Effects from the docs of NgRx ESLint.

like image 40
timdeschryver Avatar answered Sep 14 '25 10:09

timdeschryver