-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.js
34 lines (30 loc) · 1.03 KB
/
store.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
import { proxy } from 'valtio';
const state = proxy({
cartItems: [],
userId: "",
addItem(item) {
// Check if the item is already in the cart
const existingItem = this.cartItems.find((cartItem) => cartItem.id === item.id);
if (existingItem)
{
existingItem.count += 1;
}
else {
// If the item is not in the cart, add it as a new item
this.cartItems.push({ id: item.id, count: 1 });
}
},
removeItem(item) {
// Find the index of the item in the cart
const itemIndex = this.cartItems.findIndex((cartItem) => cartItem.id === item.id);
if (itemIndex !== -1) {
// If the item is found in the cart, decrease its count
this.cartItems[itemIndex].count -= 1;
if (this.cartItems[itemIndex].count === 0) {
// If the count becomes zero, remove the item from the cart
this.cartItems.splice(itemIndex, 1);
}
}
},
});
export default state;