-
Notifications
You must be signed in to change notification settings - Fork 4
/
CartReducer.js
55 lines (50 loc) · 1.87 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
import { createSlice } from "@reduxjs/toolkit";
export const CartSlice = createSlice({
name:"cart",
initialState:{
cart:[],
},
reducers:{
addToCart:(state,action) => {
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);
if (itemPresent) {
itemPresent.quantity++;
} else {
// Handle the case when the item is not found
console.log(`Item with id ${action.payload.id} not found in cart`);
}
},
decrementQuantity: (state, action) => {
const itemPresent = state.cart.find(item => item.id === action.payload.id);
if (itemPresent) {
if (itemPresent.quantity === 1) {
const removeItem = state.cart.filter(item => item.id !== action.payload.id);
state.cart = removeItem;
} else {
itemPresent.quantity--;
}
} else {
// Handle the case when the item is not found
console.log(`Item with id ${action.payload.id} not found in cart`);
}
}
,
cleanCart:(state) => {
state.cart = [];
}
}
});
export const {addToCart,removeFromCart,incrementQuantity,decrementQuantity,cleanCart} = CartSlice.actions;
export default CartSlice.reducer;