index.js
export const addToCart = (itemId) => {
return {
type: ADD_TO_CART,
payload: {
quantity: 1,
itemId
}
}
}
export const removeFromCart = (itemId) => {
return {
type: REMOVE_FROM_CART,
payload: {
itemId
}
}
}
export const setQuantity = (itemId, quantity) => {
return {
type: SET_QUANTITY,
payload: {
itemId,
quantity: quantity
}
}
}
itemReducer.js
const itemReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_TO_CART:
return Object.assign({}, state, {
cartItems: [...state.cartItems, action.payload]
})
case REMOVE_FROM_CART:
return Object.assign({}, state, {
cartItems: state.cartItems.filter(el => el.itemId !== action.payload.itemId)
})
case SET_QUANTITY:
let idx = state.cartItems.findIndex(el => el.itemId === action.payload.itemId)
state.cartItems[idx].quantity = action.payload.quantity
return Object.assign({}, state, {
cartItems: state.cartItems
})
default:
return state;
}
}
const handleQuantityChange = (quantity, itemId) => {
dispatch(setQuantity(itemId, quantity))
}
const handleDelete = (itemId) => {
setCheckedItems(checkedItems.filter((el) => el !== itemId))
dispatch(removeFromCart(itemId))
}
ItemListContainer.js
const handleClick = (item) => {
if (!cartItems.map((el) => el.itemId).includes(item.id)) {
dispatch(notify(`장바구니에 ${item.name}이(가) 추가되었습니다.`))
dispatch(addToCart(item.id))
}
else {
dispatch(notify('이미 추가된 상품입니다.'))
}
}