-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddToCart.js
62 lines (48 loc) · 2.1 KB
/
addToCart.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { getCartProductFromLS } from "./getCartProducts";
import { showToast } from "./showToast";
import { updateCartValue } from "./updateCartValue";
// -----------------------------------------------------
// to get the cart data from localStorage
// to update the cart value and also to get the data always ready from localStorage
// --------------------------------------------------------
getCartProductFromLS();
// -----------------------------------------------------
// to add the data into localStorage
// --------------------------------------------------------
export const addToCart = (event, id, stock) => {
let arrLocalStorageProduct = getCartProductFromLS();
const currentProdElem = document.querySelector(`#card${id}`);
let quantity = currentProdElem.querySelector(".productQuantity").innerText;
let price = currentProdElem.querySelector(".productPrice").innerText;
// console.log(quantity, price);
price = price.replace("₹", "");
let existingProd = arrLocalStorageProduct.find(
(curProd) => curProd.id === id
);
console.log(existingProd);
if (existingProd && quantity > 1) {
quantity = Number(existingProd.quantity) + Number(quantity);
price = Number(price * quantity);
let updatedCart = { id, quantity, price };
updatedCart = arrLocalStorageProduct.map((curProd) => {
return curProd.id === id ? updatedCart : curProd;
});
console.log(updatedCart);
localStorage.setItem("cartProductLS", JSON.stringify(updatedCart));
//show toast when product added to the cart
showToast("add", id);
}
if (existingProd) {
// alert("bhai duplicate hai");
return false;
}
//todo Don't Forget To LIKE SHARE & SUBSCRIBE TO Vats TECHNCIAL YOUTUBE CHANNEL 👉 https://www.youtube.com/Vatstechnical
price = Number(price * quantity);
quantity = Number(quantity);
arrLocalStorageProduct.push({ id, quantity, price });
localStorage.setItem("cartProductLS", JSON.stringify(arrLocalStorageProduct));
//update the cart button value
updateCartValue(arrLocalStorageProduct);
//show toast when product added to the cart
showToast("add", id);
};