Skip to content

Instantly share code, notes, and snippets.

@timdeschryver
Created June 6, 2018 17:15
Show Gist options
  • Save timdeschryver/3ad3482d03211d5ea470cf38c3eb8ef7 to your computer and use it in GitHub Desktop.
Save timdeschryver/3ad3482d03211d5ea470cf38c3eb8ef7 to your computer and use it in GitHub Desktop.
@State<CartStateModel>({
name: 'cartItems',
defaults: {
cartItems: {},
},
})
export class CartState {
@Action(AddToCart)
addProduct(ctx: StateContext<CartStateModel>, action: AddToCart) {
const state = ctx.getState();
ctx.setState({
...state,
cartItems: {
...state.cartItems,
[action.payload.sku]: (state.cartItems[action.payload.sku] || 0) + 1,
},
});
}
@Action(RemoveFromCart)
removeProduct(ctx: StateContext<CartStateModel>, action: RemoveFromCart) {
const state = ctx.getState();
ctx.patchState({
cartItems: {
...state.cartItems,
[action.payload.sku]: Math.max((state.cartItems[action.payload.sku] || 0) - 1, 0),
},
});
}
@Action(EmptyCart)
emptyCart(ctx: StateContext<CartStateModel>, action: EmptyCart) {
ctx.setState({ cartItems: {} });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment