-
Notifications
You must be signed in to change notification settings - Fork 0
/
cart-slice.js
45 lines (43 loc) · 1.53 KB
/
cart-slice.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
import { createSlice } from "@reduxjs/toolkit";
const cartSlice = createSlice({
name: "cart",
initialState: { items: [], totalQuantity: 0 },
reducers: {
replaceCart(state, action) {
state.totalQuantity = action.payload?.totalQuantity || 0;
state.items = action.payload?.items || [];
},
addItemToCart(state, action) {
state.totalQuantity++;
const newItem = action.payload.item;
const existingItem = state.items.find(
(item) => item.id === newItem.id
);
if (existingItem) {
existingItem.quantity += 1;
existingItem.totalPrice += newItem.price;
} else {
state.items.push({
id: newItem.id,
name: newItem.title,
quantity: 1,
price: newItem.price,
totalPrice: newItem.price,
});
}
},
removeItemFromCart(state, action) {
state.totalQuantity--;
const id = action.payload.id;
const existingItem = state.items.find((item) => item.id === id);
if (existingItem.quantity === 1) {
state.items = state.items.filter((item) => item.id !== id);
} else {
existingItem.quantity -= 1;
existingItem.totalPrice -= existingItem.price;
}
},
},
});
export const cartActions = cartSlice.actions;
export default cartSlice;