Search code examples
actionngxs

Multi dispatching or nested dispatching


I have store which has two fields:

  • items: Item[]
  • money: number

When user buys item I call to apiService and if the response from the server allows you to add an item (the server will check if the user has enough money) I can make two changes in my store:

  1. push new item to array
  2. decrease money

I am confused about what is good practise about dispatching actions... Which way is the best?

  1. Multi-dispatching - dispatch AddItem action and DecreaseMoney action:
store.dispatch([new AddItem(), new DecreaseMoney()]);
  1. Subscribe AddItem action and dispatch DecreaseMoney action when first is successful:
this.actions$.pipe(ofActionSuccessful(AddItem)).subscribe(() => {store.dispatch(new DecreaseMoney()});
  1. Dispatch DecreaseMoney action inside AddItem action:
@Action(AddItemAction)
  AddItem({ getState, setState }: StateContext<any>) {
    const state = getState();
    return this.http.post(`${apiUrl}/buy`, {}).pipe(
      tap(newItem => {
        setState({...state, items: [...state.items, newItem]});
        dispatch(new DecreaseMoney()); // <---
      })
    );
  }

Solution

  • if the actions do not mutate the same piece of state, I would recommend using multi-dispatching as it is less verbose. If you depend on a returned response from your first async action, I think your nested setup is logical. However, it doesn't look like you pass in anything to DecreaseMoney()...so the first option seems best.

    edit:

    I would go with option 2 then as this could be a specific scenario. If you put all the logic in your action, you are coupling the DecreaseMoney() to AddItem(). By putting the business logic within your component/container, you can create reusable actions. That is what I would do, personally.