-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCartReducer.js
56 lines (52 loc) · 1.51 KB
/
CartReducer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { createSlice } from "@reduxjs/toolkit";
export const CartSlice = createSlice({
name: "cart",
initialState: {
cart: [],
},
reducers: {
addToCart: (state, action) => {
//if this statement is true, then the item is already in the cart
const itemPresent = state.cart.find(
(item) => item.id === action.payload.id
);
if (itemPresent) {
itemPresent.quantity++;
} else {
state.cart.push({ ...action.payload, quantity: 1 });
}
},
removeFromCart: (state, action) => {
const removeItem = state.cart.filter(
(item) => item.id !== action.payload.id
);
state.cart = removeItem;
},
incrementQuantity: (state, action) => {
const itemPresent = state.cart.find(
(item) => item.id === action.payload.id
);
itemPresent.quantity++;
},
decrementQuantity: (state, action) => {
const itemPresent = state.cart.find(
(item) => item.id === action.payload.id
);
if(itemPresent.quantity == 1){
itemPresent.quantity = 0;
const removeItem = state.cart.filter(
(item) => item.id !== action.payload.id
);
state.cart = removeItem;
}
else{
itemPresent.quantity--;
}
},
cleanCart: (state)=>{
state.cart = [];
}
},
});
export const {addToCart, removeFromCart, incrementQuantity, decrementQuantity, cleanCart} = CartSlice.actions;
export default CartSlice.reducer;