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?
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.