Skip to content

Instantly share code, notes, and snippets.

@jkantr
Forked from ac205/CartReducer.jsx
Last active December 10, 2019 00:05
Show Gist options
  • Save jkantr/6546b65c0f51795c72cfadf9bfd4a972 to your computer and use it in GitHub Desktop.
Save jkantr/6546b65c0f51795c72cfadf9bfd4a972 to your computer and use it in GitHub Desktop.
Cart Reducer
const cartReducer = (state = {
cartItems: 0,
items: products,
cartContents: [],
}, action) => {
switch (action.type) {
case "ADD_TO_CART": {
const existingItem = state.cartContents.find(item => {
return item.id === Number(action.payload);
});
let newCart;
if (existingItem) {
newCart = state.cartItems.map(item => {
if (item.id === Number(action.payload)) {
return { ...item, count: item.count + 1}
}
return item;
});
} else {
newCart = [
...state.cartItems,
state.items[action.payload],
];
}
return {
...state,
cartItems: state.cartItems + 1,
cartContents: newCart,
};
break;
}
default:
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment