-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCartReducer.js
44 lines (39 loc) · 1.38 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
import {createSlice} from '@reduxjs/toolkit';
export const CartSlice = createSlice({
name:'cart',
initialState:{
cart:[],
},
reducers:{
addToCart:(state,action)=>{
const itemPresnt=state.cart.find((item)=>item.id === action.payload.id);
if(itemPresnt){
itemPresnt.quantity++;
}else{
state.cart.push({...action.payload,quantity:1});
}
},
removeFromCart:(state,action)=>{
const removeItem=state.cart.find((item)=>item.id === action.payload.id);
state.cart = removeItem;
},
incrementQuantity:(state,action)=>{
const itemPresnt=state.cart.find((item)=>item.id === action.payload.id);
if(itemPresnt){
itemPresnt.quantity++;
}
},
decrementQuantity:(state,action)=>{
const itemPresnt=state.cart.find((item)=>item.id === action.payload.id);
if(itemPresnt == 1){
itemPresnt.quantity = 0;
const removeItem=state.cart.filter((item)=>item.id === action.payload.id);
state.cart = removeItem;
}else{
itemPresnt.quantity--;
}
}
}
})
export const {addToCart,removeFromCart,incrementQuantity,decrementQuantity} = CartSlice.actions;
export default CartSlice.reducer;