How to dispatch multiple ngrx actions at the same time

ngrx dispatch multiple actions sequentially
store.dispatch multiple actions
ngrx effects listen to multiple actions
ngrx dispatch action after another action
ngrx 8 dispatch multiple actions
ngrx dispatch same action multiple times
ngrx chain actions
ngrx dispatch action from reducer

I'm using ngrx and have a scenerio where I need to dispatch 2 actions at the same time. My state has properties for updating and updated and looks like below.

//from reducer
const defaultCardState: CardState = {
    ids: [],
    entities: {},
    loaded: false,
    loading: false,
    adding: false,
    added: false,
    updating: false,
    updated: false,
    deleting: false,
    deleted: false
};

These are the actions I'm dispatching from my component

this.store.dispatch(fromCard.updateCard({id: id1, changes: {name: name1}}))
this.store.dispatch(fromCard.updateCard({id: id2, changes: {name: name2}}))

Below are my action, reducer and effect

//Update Card Actions
export const updateCard = createAction('[Cards] Update Card', props<{id: string, changes: any}>())
export const updateCardSuccess = createAction('[Cards] Update Card Success', props<{changes: any}>());
export const updateCardFail = createAction('[Cards] Update Card Fail')

//Reducer
on(fromCards.updateCard, (state) => ({...state, updating: true, updated: false})),
    on(fromCards.updateCardSuccess, (state, action: any) => ({...cardAdapter.updateOne(action.changes, state), updated: true, updating: false})),
    on(fromCards.updateCardFail, (state, action: any) => fromCards.updateCardFail),

//Update Card Effect
updateCard$: Observable<Action> = createEffect(() => this.actions$.pipe(
    ofType(fromCardActions.updateCard),
    map((action: any) => { return {id: action.id, changes: action.changes}}),
    switchMap((action: any) => this.cardService.updateCard(action).pipe(
        map((res) => (fromCardActions.updateCardSuccess({changes: action }))),
        catchError(() => of(fromCardActions.updateCardFail))
    ))
))

What is the best way to dispatch these actions one after the other so the updating and updated fields don't conflict? If I run just one of these it works but if I dispatch them both together like shown above, only one completes. I see that both actions get dispatched but only one success action gets dispatched.

You can dispatch multiple action in your effect and I would recommend you do that only in the effect

Consider example below

@Effect()
dispatchMultiAction$: Observable<Action> = this.actions$.pipe(
    ofType<SomeAction.Dispatch>(someActions.Dispatch),
    switchMap(_ =>
        of(
            new someActions.InitData(),
            new someActions.GetData(),
            new someActions.LoadData()
        )
    )
);

Dispatching Multiple Actions from NGRX Effects - Austin, I hope you enjoyed the post, if you liked it follow me on Twitter and Github for more JavaScript tips/opinions/projects/articles/etc! If you need a single @Effect stream to have multiple side-effects i.e. dispatch more than one action, you can use Rx.Observable.of in conjunection with mergeMap: import { Oservable } from 'rxjs/Observable';@Injectable()class Effects { @Effect() loadList$ = this.actions$ .ofType(this.actions.LOAD_LIST) .map(action => action.payload) .switchMap(id => { return this.service.list(id) .map(res => res.json()) .mergeMap(list => this.actions.setList(list)) .mergeMap(action => { // Here we return an

Similar to Tony's answer, but using the correct operator:

@Effect()
dispatchMultiAction$: Observable<Action> = this.actions$.pipe(
    ofType<SomeAction.Dispatch>(someActions.Dispatch),
    mergeMap(_ => [
            new someActions.InitData(),
            new someActions.GetData(),
            new someActions.LoadData()
        ])
    )
);

Dispatch multiple actions at once · Issue #468 · ngrx/platform · GitHub, Add the ability to dispatch multiple actions without emitting a new state for each action but only once all action are processed. So instead of. store. Yeah I also had in mind creating an higher order action but it felt like doing this.store.dispatch({type: 'HIGHORDER', payload: [Action1, Action2]}) Wasn't worth the trouble so I went with a plain array directly. Batching multiple actions is better handled in your reducer. Doing it on the reducer means doing more complicated reducers.

You don't, you have a different action with a payload that takes an array of cards instead of a single card and then the reducer returns the new state updated with the multiple cards. Your api should also be able to take an array so your effect can send multiple to the server.

Updating multiple areas of your ngrx redux store with a single action , But they are also able to dispatch multiple actions in response to a single action. So my prefered solution is quite simple. Dispatch the DeactivateUser action and have an ngrx effect respond to call the WebAPI and return both the DeactivateUserSuccess and DeactivateOrdersSuccess actions. Easy as that. Hi, First of all, thank you for the course. It is a great learning resource. I am trying to dispatch multiple actions on a single effect. I don&#39;t believe you cover that in your course. I was wo

Technically it is really bad practice use action to dispatch another multiple actions. It is increased complicates of the application. After some time you can not debug and understand why and were actions will be dispatched. This video Mike Ryan describe Good Action Hygiene with NgRx: https://youtu.be/JmnsEvoy-gY?t=285

Saving Multiple Entities, Many apps must save several entities at the same time in the same transaction. methods make it easier to create and dispatch all of the entity cache actions. The component dispatches the same actions in the same places. If both components are active at the same time, the first component to initialize will trigger the HTTP request.

Best way to dispatch multiple actions based on success response , Best way to dispatch multiple actions based on success response. Loving angular and would like to know how best to test my application or do TDD with it. For the time being, i am not creating, nor planning to use a SSO, my thinking is that  Actions are one of the main building blocks in NgRx. Actions express unique events that happen throughout your application. From user interaction with the page, external interaction through network requests, and direct interaction with device APIs, these and more events are described with actions.

Dispatching Multiple Actions from NGRX Effects, Dispatching Multiple Actions from NGRX Effects. Austin, Medium Subscribe to our Angular Typescript Trends and get it before everyone else. Subscribe. In my NgRx Tutorial, I wrote about setting up NgRx in your Angular 6 application. Now it’s time to focus on actions, reducers and effects. These are the heart and soul of your NgRx code and will be the ones you use most on a day to day basis.

Managing different slices of the same NgRx state, You need to create multiple of the same components and each If we only want to show one counter instance at a time, things become complex. A quick To update the counter value we dispatch an increment action and a  Modifying your Application State by Dispatching Actions Most Redux apps have a set of functions, called "action creators", that are used to set up and dispatch actions. In Angular, it's convenient to define your action creators as @Injectable() services, decoupling the dispatch, creation and side-effect logic from the @Component classes in your

Comments
  • It's cleaner to do this using mergeMap.
  • is there a reason you didn't use the "of" operator. I can't figure out why it is sometimes used to dispatch actions and sometimes not.
  • You might consider reading from learnrxjs. They have very good descriptions for each operator.
  • Thanks. I think I understand what the of operator does but I’m unsure why sometimes the action is dispatched as an observable like Tony shows above and sometimes not like in your example
  • The only reason Tony used of([]) is because switchMap will only return one observable. Essentially, what he's done is a workaround to return multiple actions. However, using mergeMap we can return multiple actions properly.
  • Thanks! So I would create a service that accepts an array and would make n number of calls to the backend to make the changes?
  • The point of making your api accept an array is so you can bulk update in a single call rather than round tripping the server.
  • Linking to a YouTube video is not an acceptable answer. It is fine for a comment but it is not an answer. At least explain the contents of what is in the video and then link to the video as a reference.
  • @AdrianBrand Thank you for your advice. I changed my answer. I shared this link because I think It is very important video to understand the architecture of actions in ngrx.
  • Thanks! The video was actually pretty eye-opening. I have been reusing actions and have seen some of the pitfalls from that. So he mentions that unique event actions create more actions but they'll create equally as many effects and reducers too right?