Search code examples
angularrxjsngrx

Angular ngRx Dispatch Second Action with data from First Action


im working in Angular 13 project and i use ngRx store, i have the following effects that works fine :

searchEnterpriseEffect: Observable<Action> = createEffect(

    () => this.effectActions.pipe(

        ofType(EnterpriseActionsTypes.SEARCH_ENTERPRISE),

        switchMap((action: EnterpriseActions) => {

            return this.enterpriseService.getEnterpriseById(action.payload)
                .pipe(
                    map((enterprise) => new SearchEnterpriseActionSuccess(enterprise)),

                    catchError((err) => of(new SearchEnterpriseActionError(err.status)))
                )
        })
    )
);

my issue is that i want to get the enterprise object Id after SearchEnterpriseActionSuccess finish then dispatch a new store action called SearchDemandeData(enterpriseId) that takes the data from state returned by previous action.

do you have any idea please how i can do this correctly.

Regards.


Solution

  • You should create other effect that listens to SearchEnterpriseActionSuccess, extract the id from the enterprise and dispatch the new action SearchDemandeData with the extracted id.

    I don't know your exact implementation, but it should be something similar to the following.

    searchDemandeOnEnterpriseSuccessEffect: Observable<Action> = createEffect(
    
      () => this.effectActions.pipe(
    
        // filter by SearchEnterpriseActionSuccess
        ofType(EnterpriseAPIActionsTypes.SEARCH_ENTERPRISE_SUCCESS),
    
        // map the action to SearchDemandeData Action using the enterprise id
        map((action: SearchEnterpriseActionSuccess) => 
          (new SearchDemandeData(action.enterprise.id))
        )
    
      )
    
    );
    

    Cheers