Imagine you could get service by groups…

Dispatch multiple Actions from a single Effect using an action array

Udi Mazor

--

There might be a situation where you need to dispatch more than one action from a single effect. Even further you can sometimes want to select which actions to dispatch according to a given state or set of conditions.

I found a very nice solution to this situation. If you need to dispatch multiple actions then why not use an array? If this is good for containing several variables of the same type then there is no reason not to use it for dispatching multiple actions.

So the first thing we need to do is to create a local Array of Actions. Well, do it inside the effect so the variable will be local.

let actionsArray = new Array<action>();

And now we can push whatever action we want to dispatch to this array. We can be selective on which action we are pushing inside that array and use conditions for that purpose.

if(IState.routerState.queryParams.companyId){
let companyId = IState.routerState.queryParams.companyId;
actionsArray.push(new directoryActions.setCompanyId(companyId))
}

Now you can dispatch the array instead of dispatching to a single action.

readRouteFilters$: Observable<Action> = this.actions$.pipe(
ofType(DirectoryFormActionTypes.GetFormInputsSuccess),
withLatestFrom(this.store),
map(([never, IState]) => IState),
concatMap((IState) => actionsArray))

You can also create the logic for adding or removing actions from the array inside the action itself. This way instead of dispatching action after action. It will be wiser to give meaningful names to the array that will reflect the state changes it responsible for.

--

--

Udi Mazor

An enthusiastic front end developer with a big fashion to Angular.