Skip to content

Instantly share code, notes, and snippets.

@ac205
Created December 11, 2019 00:04
Show Gist options
  • Save ac205/c82bd8b971911bebf5e97fecba398773 to your computer and use it in GitHub Desktop.
Save ac205/c82bd8b971911bebf5e97fecba398773 to your computer and use it in GitHub Desktop.
cart
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 id = Number(action.payload);
if (state.cartContents[id].count === 0) {
return state
} else {
let subtractItem = state.cartContents.map(item => {
if (item.id === Number(action.payload)) {
if (item.count === 0) {
return item
} else
return {...item, count: item.count - 1 }
}
return item;
});
state = {
...state,
cartItems: state.cartItems === 0 ? 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