generated from ibm-developer-skills-network/coding-project-template
-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
Copy pathCartSlice.jsx
36 lines (30 loc) · 992 Bytes
/
CartSlice.jsx
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
import { createSlice } from '@reduxjs/toolkit';
export const CartSlice = createSlice({
name: 'cart',
initialState: {
items: [], // Initialize items as an empty array
},
reducers: {
addItem: (state, action) => {
const { name, image, cost } = action.payload;
const existingItem = state.items.find(item => item.name === name);
if (existingItem) {
existingItem.quantity++;
} else {
state.items.push({ name, image, cost, quantity: 1 });
}
},
removeItem: (state, action) => {
state.items = state.items.filter(item => item.name !== action.payload);
},
updateQuantity: (state, action) => {
const { name, quantity } = action.payload;
const itemToUpdate = state.items.find(item => item.name === name);
if (itemToUpdate) {
itemToUpdate.quantity = quantity;
}
}
}
});
export const { addItem, removeItem, updateQuantity } = CartSlice.actions;
export default CartSlice.reducer;