Maxime Gélinas
Maxime Gélinas

Reputation: 2330

NGXS - Good Practices: Passing service required params in action or getting it from state?

When handling a dispatched action, the state need some params to pass to the service such as the ID of the resource in order to perform the action. How should I get these params?

1. From the state:

  @Action(AddCartItem)
  addCartItem({ getState, patchState }: StateContext<CartStateModel>, { item }: AddCartItem) {
    const cartId = getState().cartId;
    return this.service.addCartItem(cartId, item).pipe(
      tap(item => patchState({ /* [...] */ })),
    );
  }

Pros:

Cons:


2. From the action:

  @Action(AddCartItem)
  addCartItem({ getState, patchState }: StateContext<CartStateModel>, { cartId, item }: AddCartItem {
    return this.service.addCartItem(cartId, item).pipe(
      tap(item => patchState({ /* [...] */ })),
    );
  }

Pros:

Cons:


In my opinion, option 2 looks better, but am I missing something? Is option 2 can cause unwanted side effects?

Upvotes: 3

Views: 1642

Answers (2)

Reactgular
Reactgular

Reputation: 54801

Don't couple your actions to the current state, because you might not be able replay the action, skip actions or rollback actions using a Redux debugger.

It's better if your actions are incremental movements in the change of the state from the previous state, and do not directly depend upon the previous state.

It also makes testing more difficult, because now the unit test needs to know more about the pre-existing state to test the action. If the action contains more information in the payload, then the test conditions are easier to set up.

Upvotes: 3

Chris Hailey
Chris Hailey

Reputation: 209

i think the answer would be very tied to the user story, but i personally have both patterns in my app…… when the state contains only one possible value for the action it made sense to not pass it however, when the service param had n+1 possible values i pass it in the action

Upvotes: 0

Related Questions