Skip to content

Instantly share code, notes, and snippets.

@timdeschryver
Last active May 26, 2018 14:58
Show Gist options
  • Save timdeschryver/697f0d892385c613ceab8fc04f84eac4 to your computer and use it in GitHub Desktop.
Save timdeschryver/697f0d892385c613ceab8fc04f84eac4 to your computer and use it in GitHub Desktop.
export const reducer = produce<State, CartActions>((draft, action) => {
switch (action.type) {
case CartActionTypes.AddToCart:
draft.cartItems[action.payload.sku] = (draft.cartItems[action.payload.sku] || 0) + 1;
return;
case CartActionTypes.RemoveFromCart:
const newAmount = draft.cartItems[action.payload.sku] - 1;
if (newAmount > 0) {
draft.cartItems[action.payload.sku] = newAmount;
return;
}
delete draft.cartItems[action.payload.sku];
// or
// draft.cartItems[action.payload.sku] =
// Math.max((draft.cartItems[action.payload.sku] || 0) - 1, 0);
return;
case CartActionTypes.EmptyCart:
return initialState;
}
}, initialState);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment