Advertisement
RupeshAcharya60

finedlsajf

Aug 20th, 2024
18
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.38 KB | None | 0 0
  1. const result = document.querySelector(".product-list"); // all the products container
  2. const categoryButtonsContainer = document.querySelector(".category-buttons"); //buttons container
  3. const input = document.querySelector("input"); //search bar
  4.  
  5. const API_BASE_URL = "https://dummyjson.com/products";
  6.  
  7. const fetchByCategory = (category) =>
  8. fetch(`${API_BASE_URL}/category/${category}`).then((response) =>
  9. response.json()
  10. );
  11.  
  12. const fetchBySearch = (searchValue) =>
  13. fetch(`${API_BASE_URL}/search?q=${searchValue}`).then((response) =>
  14. response.json()
  15. );
  16.  
  17. const fetchAllProducts = () =>
  18. fetch(API_BASE_URL).then((response) => response.json());
  19.  
  20.  
  21.  
  22. const fetchProductDetail = (id) =>
  23. fetch(`${API_BASE_URL}/${id}`).then((response) => response.json());
  24.  
  25. const fetchProducts = (searchValue = "", category = "") => {
  26. let fetchPromise;
  27.  
  28. if (category) {
  29. fetchPromise = fetchByCategory(category);
  30. } else if (searchValue) {
  31. fetchPromise = fetchByCategory(searchValue).then((response) => {
  32. if (response.products.length === 0) {
  33. return fetchBySearch(searchValue);
  34. }
  35. return response;
  36. });
  37. } else {
  38. fetchPromise = fetchAllProducts();
  39. }
  40. fetchPromise.then((data) => productRender(data.products));
  41. };
  42.  
  43. const productRender = (products) => {
  44. result.innerHTML = products
  45. .map(
  46. (product) => `
  47. <div class=product onclick=handleProductClick(${product.id})>
  48. <img loading="lazy" src=${product.thumbnail}>
  49. <div class=productDesc>
  50. <p>${product.title}</p>
  51. <p>Price: $${product.price}</p></div>
  52.  
  53. </div>`
  54. )
  55. .join("");
  56. };
  57.  
  58. const fetchCategoryList = () => {
  59. fetch("https://dummyjson.com/products/category-list")
  60. .then((res) => res.json())
  61. .then((categories) => {
  62. categoryButtonsContainer.innerHTML = categories
  63. .map(
  64. (category) =>
  65. `<button class = category-button data-category="${category}">${category}</button>
  66. `
  67. )
  68. .join("");
  69.  
  70. document.querySelectorAll(".category-button").forEach((button) => {
  71. button.addEventListener("click", () => {
  72. fetchProducts(input.value, button.dataset.category);
  73. });
  74. });
  75. })
  76. .catch((error) => console.error("Error fetching categories:", error));
  77. };
  78.  
  79. fetchProducts();
  80. fetchCategoryList();
  81.  
  82. const debounceFunction = (fn, delay) => {
  83. let timer;
  84. return (...args) => {
  85. clearTimeout(timer);
  86. timer = setTimeout(() => {
  87. fn(...args);
  88. }, delay);
  89. };
  90. };
  91.  
  92. const callDebounce = debounceFunction(fetchProducts, 500);
  93.  
  94. input.addEventListener("input", (e) => {
  95. callDebounce(e.target.value);
  96. });
  97.  
  98.  
  99. function handleProductClick(id){
  100. let fetchPromise;
  101.  
  102. fetchPromise = fetchProductDetail(id)
  103.  
  104.  
  105. fetchPromise.then((product)=>
  106. {
  107. createProductHTML(product);
  108. })
  109.  
  110. }
  111.  
  112.  
  113.  
  114.  
  115.  
  116. function createProductHTML(product) {
  117. const reviewsHTML = product.reviews.map(review => `
  118. <div class="review">
  119. <div class="review-rating">${'★'.repeat(review.rating)}${'☆'.repeat(5-review.rating)}</div>
  120. <p class="review-comment">"${review.comment}"</p>
  121. <p class="review-author">By ${review.reviewerName} on ${new Date(review.date).toLocaleDateString()}</p>
  122. </div>
  123. `).join('');
  124.  
  125. const html = `
  126. <div class="product" id="product-${product.id}">
  127. <div class="product-header">
  128. <h2>${product.title}</h2>
  129. <span class="product-brand">${product.brand}</span>
  130. </div>
  131. <div class="product-main">
  132. <div class="product-image">
  133. <img src="${product.thumbnail}" alt="${product.title}">
  134. </div>
  135. <div class="product-info">
  136. <div class="product-price-rating">
  137. <span class="product-price">$${product.price.toFixed(2)}</span>
  138. <span class="product-discount">-${product.discountPercentage}%</span>
  139. <div class="product-rating">${'★'.repeat(Math.round(product.rating))}${'☆'.repeat(5-Math.round(product.rating))} ${product.rating}</div>
  140. </div>
  141. <p class="product-description">${product.description}</p>
  142. <div class="product-meta">
  143. <p><strong>Category:</strong> ${product.category}</p>
  144. <p><strong>SKU:</strong> ${product.sku}</p>
  145. <p><strong>Stock:</strong> ${product.stock}</p>
  146. <p><strong>Weight:</strong> ${product.weight} oz</p>
  147. <p><strong>Dimensions:</strong> ${product.dimensions.width}" x ${product.dimensions.height}" x ${product.dimensions.depth}"</p>
  148. </div>
  149. <div class="product-tags">
  150. ${product.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
  151. </div>
  152. </div>
  153. </div>
  154. <div class="product-details">
  155. <h3>Additional Information</h3>
  156. <p><strong>Warranty:</strong> ${product.warrantyInformation}</p>
  157. <p><strong>Shipping:</strong> ${product.shippingInformation}</p>
  158. <p><strong>Availability:</strong> ${product.availabilityStatus}</p>
  159. <p><strong>Return Policy:</strong> ${product.returnPolicy}</p>
  160. <p><strong>Minimum Order Quantity:</strong> ${product.minimumOrderQuantity}</p>
  161. </div>
  162. <div class="product-reviews">
  163. <h3>Customer Reviews</h3>
  164. ${reviewsHTML}
  165. </div>
  166. </div>
  167. `;
  168.  
  169.  
  170. result.innerHTML = html;
  171. return html;
  172. }
  173.  
  174.  
  175.  
  176.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement