-
Notifications
You must be signed in to change notification settings - Fork 909
Expand file tree
/
Copy pathcart.js
More file actions
92 lines (72 loc) · 1.73 KB
/
cart.js
File metadata and controls
92 lines (72 loc) · 1.73 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
export let cart;
loadFromStorage();
export function loadFromStorage() {
cart = JSON.parse(localStorage.getItem('cart'));
if (!cart) {
cart = [{
productId: 'e43638ce-6aa0-4b85-b27f-e1d07eb678c6',
quantity: 2,
deliveryOptionId: '1'
}, {
productId: '15b6fc6f-327a-4ec4-896f-486349e85a3d',
quantity: 1,
deliveryOptionId: '2'
}];
}
}
function saveToStorage() {
localStorage.setItem('cart', JSON.stringify(cart));
}
export function addToCart(productId) {
let matchingItem;
cart.forEach((cartItem) => {
if (productId === cartItem.productId) {
matchingItem = cartItem;
}
});
if (matchingItem) {
matchingItem.quantity += 1;
} else {
cart.push({
productId: productId,
quantity: 1,
deliveryOptionId: '1'
});
}
saveToStorage();
}
export function removeFromCart(productId) {
const newCart = [];
cart.forEach((cartItem) => {
if (cartItem.productId !== productId) {
newCart.push(cartItem);
}
});
cart = newCart;
saveToStorage();
}
export function updateDeliveryOption(productId, deliveryOptionId) {
let matchingItem;
cart.forEach((cartItem) => {
if (productId === cartItem.productId) {
matchingItem = cartItem;
}
});
matchingItem.deliveryOptionId = deliveryOptionId;
saveToStorage();
}
export function loadCart(fun) {
const xhr = new XMLHttpRequest();
xhr.addEventListener('load', () => {
console.log(xhr.response);
fun();
});
xhr.open('GET', 'https://supersimplebackend.dev/cart');
xhr.send();
}
export async function loadCartFetch() {
const response = await fetch('https://supersimplebackend.dev/cart');
const text = await response.text();
console.log(text);
return text;
}