Reputation: 2330
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?
@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:
@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
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
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