Search code examples
angularcqrsngxs

What is the purpose of the success / failed action events for async actions with ngxs?


The sample apps for ngxs typically dispatch discrete success / failed actions for every asynchronous action.

For example: https://github.com/tommythongnguyen/Ngxs-Pizza-Order/blob/master/src/app/products/store/pizzas.state.ts#L45

To me it makes more sense to simply observe the dispatch, if you want to wait for an action to succeed/fail.

For most cases, you would only care about failure, as to read the data back out of the store, I'd be expect to be using independent selects rather than looking at the action stream.

In terms of handling failure, I think that normally it would be the dispatcher who would be interested in handling a failure.

Stackblitz showing my preferred approach: https://stackblitz.com/edit/angular-ngxs-so-question

Is this pattern just a hold over from flux / redux where the dispatches don't return a handle on an async action? Or is some benefit to this approach that I'm not seeing?


Solution

  • In my experience with NGXS so far, we've used both your preferred approach, and in some cases explicit success/failure actions.

    Where we used explicit actions was typically where we had one state wanting to respond to the change in another.

    E.g. having a state that capture some common reference data, but we can only load that after the user has logged in. We dispatch a LoginSuccess action, and have the ReferenceDataState respond to that to call the API and fetch reference data.

    Another case we have is that the caller wants to know some data e.g an ID of an entity created by the originating action. Store's dispatch function returns an Observable with void return type, so we can use a success action to pick up that result value.