Skip to content

Instantly share code, notes, and snippets.

@ac205
Last active December 10, 2019 00:46
Show Gist options
  • Save ac205/86078eb685095f31ee907b08d7623c0f to your computer and use it in GitHub Desktop.
Save ac205/86078eb685095f31ee907b08d7623c0f 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 newCartContents;
if (existingItem) {
newCartContents = state.cartContents.map(item => {
if (item.id === Number(action.payload)) {
return { ...item, count: item.count + 1 }
}
return item;
});
} else {
newCartContents = [
...state.cartContents,
state.items[action.payload],
];
}
state = {
...state,
cartItems: state.cartItems + 1,
cartContents: newCartContents,
};
}
break;
case "SUBTRACT_ITEM": {
let subtractItem = state.cartContents.map(item => {
if (item.id === Number(action.payload)) {
return { ...item, count: item.count - 1 }
}
return item;
});
state = {
...state,
cartItems: state.cartItems - 1,
cartContents: subtractItem,
};
};
break;
case "ADD_ITEM": {
let addItem = state.cartContents.map(item => {
if (item.id === Number(action.payload)) {
return { ...item, count: item.count + 1 }
}
return item;
});
state = {
...state,
cartItems: state.cartItems + 1,
cartContents: addItem,
};
};
break;
default:
}
return state;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment