Search code examples
ngrxngrx-effects

Trigger a action upon success full response of another action ngrx


I created a ngrx effect that's responsible for sending a POST request to a back end. now i want to change the implementation little bit. if the post request is successful I want to trigger another action that responsible update my ngrx store. but I couldn't figure out how to do that.

I tried to use switch map and merge map but didn't work.

creatTour$ = createEffect(() =>
   this.actions$.pipe(
       ofType(TourAction.createTour),
        mergeMap((action) => {
            const payload = action.tour;
            const endpoint = environment.urls.tour.replace("{tourProviderId}", "1");
             const request = new ServiceRequest(endpoint, 'POST', payload, options);

             return this.requestHandlerService.invoke(request).pipe(
                map((sucessResponce) => {
                   if (sucessResponce.code === 200) {
                        TourListAction.updateTourList({ tour: [tour] }) // i want to trigger this action and
                                                                            // below action 
                     }
                   return TourAction.createTourSucess({ responce: sucessResponce.message })
                    }),
                    catchError(err => {
                        const errorMessage = JSON.stringify(err);
                        console.log(errorMessage);
                        return of(TourAction.createTourFail({ errorMessage }))
                    })
                )
            })
        )
    );

i tried this way too

return [TourAction.createTourSucess({ responce: sucessResponce.message }
        TourListAction.updateTourList({ tour: [tour] })]

it throws this error

 Property 'type' is missing in type '(({ responce: string; } 
 & TypedAction<"[Tour] Create Tour Success">) | ({ tour: Tours[]; } & 
 TypedAction<"[Tour List] Tour List Update">))[]' but required in type 
 'Action'.

is this the better way to do this.i saw there is new thing called entity should I use that for this implementation?


Solution

  • Why not update your state on the createTourSucess action?

    You can also return multiple actions:

    .pipe(
      switchMap(() => 
        return [
        TourListAction.updateTourList({ tour: [tour] }) ,  
        TourAction.createTourSucess({ responce: sucessResponce.message })
        ]
      )
    )
    

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