LocalStorage - Basit Al Fath

Minggu, 26 April 2026

LocalStorage

LocalStorage


let products = [];

const memuatProduct = async () => {
  try {
    const response = await fetch("https://fakestoreapi.com/products");
    if (!response.ok) throw new Error("Produk gagal di muat");
    products = await response.json();
    tampilProduct();
  } catch (error) {
    console.log("error saatmemuat :", error);
  }
};

function tampilProduct() {
  const container = document.getElementById("daftar_product");
  let html = "";
  products.forEach((product) => {
    html += `
    <div class="border p-4 rounded shadow">
        <img src="${product.image}" class="h-40 mx-auto object-contain mb-4">
        <p class="text-blue-600 font-semibold">${product.category}</p>
        <h2 class="font-bold mt-2 line-clamp-2">${product.title}</h2>
        <p class="text-blue-600 font-semibold">$${product.price}</p>
        <div class="flex justify-between items-center mt-3">
        <a href="#" class="inline-block rounded-md bg-gray-100 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-200 active:bg-gray-300">
          Detail
        </a>
        <a href="#" onclick="keranjang(${product.id})" class="inline-block rounded-md bg-gray-100 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-200 active:bg-gray-300">+ Keranjang</a>
        </div>
      </div>
    `;
  });
  container.innerHTML = html;
}

function keranjang(id) {
  // ambil isi keranjang lama
  let cart = JSON.parse(localStorage.getItem("keranjang")) || [];

  // cari produk dari array products
  let product = products.find((item) => item.id === id);

  // cek apakah sudah ada di keranjang
  let index = cart.findIndex((item) => item.id === id);

  if (index !== -1) {
    cart[index].qty += 1;
  } else {
    cart.push({
      id: product.id,
      title: product.title,
      price: product.price,
      image: product.image,
      qty: 1,
    });
  }

  // simpan lagi ke localStorage
  localStorage.setItem("keranjang", JSON.stringify(cart));
  tampilCart();
  alert("Produk ditambahkan ke keranjang");
  console.log(cart);
}

function tampilCart() {
  let cart = JSON.parse(localStorage.getItem("keranjang")) || [];

  const container = document.getElementById("productcart");

  // jika kosong
  if (cart.length === 0) {
    container.innerHTML =
      '<p class="text-gray-500 text-center">Keranjang masih kosong</p>';
    return;
  }

  let html = "";

  cart.forEach((item) => {
    html += `
      <div class="flex gap-3 mb-4 border-b pb-3">
        <img src="${item.image}" class="w-14 h-14 object-contain">
       
        <div class="flex-1">
          <h3 class="text-sm font-semibold line-clamp-2">${item.title}</h3>
          <p class="text-sm text-gray-500">$${item.price}</p>
          <p class="text-sm">Qty : ${item.qty}</p>
        </div>
      </div>
    `;
  });

  container.innerHTML = html;
}


tampilCart()
memuatProduct();


 


Comments


EmoticonEmoticon