forked from EslamRedaMohamed/E-Commerce-Web-Site
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetchProducts.js
102 lines (79 loc) · 2.47 KB
/
fetchProducts.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
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
93
94
95
96
97
98
99
100
// fetch all Products
const products=await fetchProducts()
async function fetchProducts() {
try {
var response = await fetch('https://dummyjson.com/products?limit=0');
var data = await response.json();
return data.products;
} catch (error) {
console.error('Error fetching products:', error);
}
finally{
console.log("Data Fetched");
}
}
// fetch single Product By Id
async function fetchProductById(id) {
try {
var response = await fetch(`https://dummyjson.com/products/${id}`);
var data = await response.json();
return data;
} catch (error) {
console.error('Error fetching product:', error);
}
}
//fetch products for category
async function dataRetriever(category) {
if(category !== "all"){
var url = `https://dummyjson.com/products/category/${category}`;
}
else{
var url = `https://dummyjson.com/products?limit=0`;
}
// Fetch data from the constructed URL
var response = await fetch(url);
var data = await response.json();
return data.products;
}
// Function to filter products based on search input
function searchProducts() {
var searchTerm = document.getElementById('search-input').value.trim().toLowerCase();
var productCards = document.querySelectorAll('.box');
productCards.forEach(card => {
var title = card.querySelector('h4').textContent.toLowerCase();
if (title.includes(searchTerm)) {
card.style.display = 'block';
} else {
card.style.display = 'none';
}
});
}
//function to init cart details and update in session storage
const addToCart = function (pId) {
var cart = []
//load cart from session storage
if (sessionStorage.getItem('cart') != null)
cart = [...JSON.parse(sessionStorage.getItem('cart'))]
//add cart item to cart
let found = false;
let getItem = cart.forEach((cartItem) => {
if (pId == cartItem.id) {
cartItem['quantity'] += 1
found = true
}
})
if (!found) {
cart.push({
'id': pId,
'quantity': 1
})
}
//update cart in session
sessionStorage.setItem('cart', JSON.stringify(cart));
console.log(sessionStorage.getItem('cart'));
//make label with cart items
let label = document.getElementById('cart-item-n')
label.innerHTML = cart.length;
}
export default products
export {fetchProductById,addToCart,dataRetriever,searchProducts}