Skip to content

Instantly share code, notes, and snippets.

@ac205
Last active December 10, 2019 13:30
Show Gist options
  • Save ac205/51f6675e27ed60f4a889d2b876bd4b57 to your computer and use it in GitHub Desktop.
Save ac205/51f6675e27ed60f4a889d2b876bd4b57 to your computer and use it in GitHub Desktop.
Subtract 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)) {
if (item.count === 0) {
return item
} else
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;
};
///////////////////////////////
const mapDispatchToProps = (dispatch) => {
return {
addItem: (id) => { dispatch({ type: 'ADD_ITEM', payload: id }) },
subtractItem: (id) => { dispatch({ type: 'SUBTRACT_ITEM', payload: id }) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment