ashil
ashil

Reputation: 181

Dispatch action in effect before return statement

I need to dispatch/trigger another ui-related action inside an effect before calling the service to fetch data without injecting the store

I managed to fix it by injecting the store in the constructor and dispatch this extra action in effect right before calling the service for fetching the data(this.store.dispatch(UIActions.startLoading()) but I am not sure if injecting the store in the effect is a good practice

recipes$ = createEffect(() => this.actions$.pipe(
        ofType(RecipeActions.FETCH_RECIPES),
        switchMap(() => this.recipeService.getRecipes().pipe(
            switchMap(recipes => [
                RecipeActions.setRecipes({ recipes }),
                UIActions.stopLoading()
            ]),
            catchError(() => EMPTY)
        ))
    ));

I wonder if there is a way to do this like using tap(() => of(UIActions.startLoading())) inside the first switchMap

Upvotes: 1

Views: 1052

Answers (1)

Pankaj
Pankaj

Reputation: 568

You're correct in the use of tap operator for your desired functionality.

However, you need to do store.dispatch instead of simply returning an of observable. Also, instead of multiple switchMap, you can use the from observable to return array of actions.

recipes$ = createEffect(() => this.actions$.pipe(
        ofType(RecipeActions.FETCH_RECIPES),
        tap(()=> this.store.dispatch(UIActions.startLoading())),
        switchMap(() => this.recipeService.getRecipes().pipe(
            map(recipes => from([
                RecipeActions.setRecipes({ recipes }),
                UIActions.stopLoading()
            ]),
            catchError(() => EMPTY)
        ))
    ));

Upvotes: 2

Related Questions