Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const result = document.querySelector(".product-list"); // all the products container
- const categoryButtonsContainer = document.querySelector(".category-buttons"); //buttons container
- const input = document.querySelector("input"); //search bar
- const API_BASE_URL = "https://dummyjson.com/products";
- const fetchByCategory = (category) =>
- fetch(`${API_BASE_URL}/category/${category}`).then((response) =>
- response.json()
- );
- const fetchBySearch = (searchValue) =>
- fetch(`${API_BASE_URL}/search?q=${searchValue}`).then((response) =>
- response.json()
- );
- const fetchAllProducts = () =>
- fetch(API_BASE_URL).then((response) => response.json());
- const fetchProductDetail = (id) =>
- fetch(`${API_BASE_URL}/${id}`).then((response) => response.json());
- const fetchProducts = (searchValue = "", category = "") => {
- let fetchPromise;
- if (category) {
- fetchPromise = fetchByCategory(category);
- } else if (searchValue) {
- fetchPromise = fetchByCategory(searchValue).then((response) => {
- if (response.products.length === 0) {
- return fetchBySearch(searchValue);
- }
- return response;
- });
- } else {
- fetchPromise = fetchAllProducts();
- }
- fetchPromise.then((data) => productRender(data.products));
- };
- const productRender = (products) => {
- result.innerHTML = products
- .map(
- (product) => `
- <div class=product onclick=handleProductClick(${product.id})>
- <img loading="lazy" src=${product.thumbnail}>
- <div class=productDesc>
- <p>${product.title}</p>
- <p>Price: $${product.price}</p></div>
- </div>`
- )
- .join("");
- };
- const fetchCategoryList = () => {
- fetch("https://dummyjson.com/products/category-list")
- .then((res) => res.json())
- .then((categories) => {
- categoryButtonsContainer.innerHTML = categories
- .map(
- (category) =>
- `<button class = category-button data-category="${category}">${category}</button>
- `
- )
- .join("");
- document.querySelectorAll(".category-button").forEach((button) => {
- button.addEventListener("click", () => {
- fetchProducts(input.value, button.dataset.category);
- });
- });
- })
- .catch((error) => console.error("Error fetching categories:", error));
- };
- fetchProducts();
- fetchCategoryList();
- const debounceFunction = (fn, delay) => {
- let timer;
- return (...args) => {
- clearTimeout(timer);
- timer = setTimeout(() => {
- fn(...args);
- }, delay);
- };
- };
- const callDebounce = debounceFunction(fetchProducts, 500);
- input.addEventListener("input", (e) => {
- callDebounce(e.target.value);
- });
- function handleProductClick(id){
- let fetchPromise;
- fetchPromise = fetchProductDetail(id)
- fetchPromise.then((product)=>
- {
- createProductHTML(product);
- })
- }
- function createProductHTML(product) {
- const reviewsHTML = product.reviews.map(review => `
- <div class="review">
- <div class="review-rating">${'★'.repeat(review.rating)}${'☆'.repeat(5-review.rating)}</div>
- <p class="review-comment">"${review.comment}"</p>
- <p class="review-author">By ${review.reviewerName} on ${new Date(review.date).toLocaleDateString()}</p>
- </div>
- `).join('');
- const html = `
- <div class="product" id="product-${product.id}">
- <div class="product-header">
- <h2>${product.title}</h2>
- <span class="product-brand">${product.brand}</span>
- </div>
- <div class="product-main">
- <div class="product-image">
- <img src="${product.thumbnail}" alt="${product.title}">
- </div>
- <div class="product-info">
- <div class="product-price-rating">
- <span class="product-price">$${product.price.toFixed(2)}</span>
- <span class="product-discount">-${product.discountPercentage}%</span>
- <div class="product-rating">${'★'.repeat(Math.round(product.rating))}${'☆'.repeat(5-Math.round(product.rating))} ${product.rating}</div>
- </div>
- <p class="product-description">${product.description}</p>
- <div class="product-meta">
- <p><strong>Category:</strong> ${product.category}</p>
- <p><strong>SKU:</strong> ${product.sku}</p>
- <p><strong>Stock:</strong> ${product.stock}</p>
- <p><strong>Weight:</strong> ${product.weight} oz</p>
- <p><strong>Dimensions:</strong> ${product.dimensions.width}" x ${product.dimensions.height}" x ${product.dimensions.depth}"</p>
- </div>
- <div class="product-tags">
- ${product.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
- </div>
- </div>
- </div>
- <div class="product-details">
- <h3>Additional Information</h3>
- <p><strong>Warranty:</strong> ${product.warrantyInformation}</p>
- <p><strong>Shipping:</strong> ${product.shippingInformation}</p>
- <p><strong>Availability:</strong> ${product.availabilityStatus}</p>
- <p><strong>Return Policy:</strong> ${product.returnPolicy}</p>
- <p><strong>Minimum Order Quantity:</strong> ${product.minimumOrderQuantity}</p>
- </div>
- <div class="product-reviews">
- <h3>Customer Reviews</h3>
- ${reviewsHTML}
- </div>
- </div>
- `;
- result.innerHTML = html;
- return html;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement