Search code examples
javascripthtmlcssjsoncart

Is there anyway I can check for duplicate in localStorage


I am creating a shopping cart with products fetch from a fake json-server. Each time I click the "add to cart" button, I want the product to be push into an array, and if it does exist in the array, I want to increase it by 1

const productGrid = document.querySelector('.grid__product');
const addToCartBtn = document.getElementsByClassName('add-to-cart-btn');
const tableBody = document.querySelector('.table__body');

eventListeners();

//all event listeners
function eventListeners() {
    window.addEventListener('DOMContentLoaded', () => {
        loadJSON();
        loadCart();
    })
    productGrid.addEventListener('click', purchaseProduct)
}

//load json file into grid display
function loadJSON() {
    fetch('http://localhost:3000/products').then(response => {
        response.json().then(data => {
            let html = '';
            data.forEach(product => {
                html += `<div class="legacy__items__detail" id='product-${product.id}'><img class='product__img' src="${product.img}" alt="OHUI">
                    <div class="legacy__items__detail__content legacy-content">
                    <h4 class='product__name'>${product.productName}</h4><a href="">
                    <p class='product__category'>${product.name}</p></a><span class="price">${product.price}<small>vnd</small></span>
                    </div>
                    <div class="legacy__items__detail__icon">
                    <div class="legacy-cta">
                    <button class='add-to-cart-btn'>Mua hàng</button>
                    <a href=""><i class="fas fa-heart"></i></a><a href=""><i class="fas fa-sync-alt"></i></a>
                    </div>
                    </div>
                    </div>`;
        })
            productGrid.innerHTML = html;
    })
})}

function purchaseProduct(e) {
    if (e.target.classList.contains('add-to-cart-btn')) {
        let product = e.target.parentElement.parentElement.parentElement;
        getProductInfo(product);
    }
}


//get product info after add-cart btn is clicked
function getProductInfo(product) {
    let productInfo =  {
        name:  product.querySelector('.product__name').textContent,
        imgSrc: product.querySelector('.product__img').src,
        category:  product.querySelector('.product__category').textContent,
        price: parseInt(product.querySelector('.price').textContent),
        count: 1,
    }
    saveProductInStorage(productInfo);
}

function saveProductInStorage(item) {
    let products = []
    localStorage.setItem('products', JSON.stringify(products));
    if(products.indexOf(item) === -1) {
        products.push(item)
    } else {
        item.count++;                          
    }
    console.log(products)
}

I have tried several method but the more I try, the more I getting stuck. Can someone please help me with this ?

Edit : I have succeed in pushing the item in the array and when there is duplicate,the quantity of the item increase, however, I wanna set the products array in the localStorage. Any help is appreciated!

    if (products.length === 0) {
        products.push(item);
        console.log(products);
        return;
    }
    for (let i = 0; i < products.length; i++) {
        if (products[i].name === item.name) {
            products[i].count++;
            console.log(products);
            return;
        }
    }
    products.push(item);
}

Solution

  • Slight change to the above answer:

    var myContent = document.getElementById("myTextarea").value;
    var savedProducts = JSON.parse(localStorage.getItem("products")) || [];
    for (var i = 0; i < savedProducts.length; i++) {
       if (JSON.parse(myContent).name === savedProducts[i].name) {
          savedProducts[i].count++;
          alert(`Found Duplicate. Not inserting again  ${myContent}`)
       } else if (i == savedProducts.length - 1) {
         alert(`Inserted ${myContent}`)
         savedProducts.push(JSON.parse(myContent));
         localStorage.setItem("names", JSON.stringify(savedProducts))
         return;
       }
    }
    

    Tested and seems to be working. enter image description here

    enter image description here

    Here is a fully functional code:

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
    
    </head>
    
    <body>
      <h1>Product Retrieve from Locastorage demo</h1>
      <textarea id="myTextarea" rows="10" cols="80"></textarea>
      <p></p>
      <button onclick="saveToCart()">Save to Cart</button>
      <button onclick="loadCart()">Load from Cart</button>
      <p id="myCart"></p>
      <script>
        var products = [];
        localStorage.setItem("products", JSON.stringify(products))
    
        function saveToCart() {
          var productInfo = document.getElementById("myTextarea").value;
          var savedProducts = JSON.parse(localStorage.getItem("products")) || [];
          if (products.length === 0) {
            products.push(JSON.parse(productInfo));
            localStorage.setItem("products", JSON.stringify(products))
            //console.log(savedProducts.length)
          } else {
            for (var i = 0; i <= savedProducts.length; i++) {
              if (JSON.parse(productInfo).name === savedProducts[i].name) {
                savedProducts[i].count++;
                //alert(`Found Duplicate at position ${i}. Not inserting again  ${productInfo}`)
                alert(`${JSON.parse(productInfo).name} already exists`)
              } else if (i == savedProducts.length - 1) {
                alert(`Inserted ${productInfo} at position ${i}`)
                savedProducts.push(JSON.parse(productInfo));
                localStorage.setItem("products", JSON.stringify(savedProducts))
                console.log(savedProducts.length)
                return;
              }
            }
          }
        }
    
        function loadCart() {
          var products = localStorage.getItem("products");
          products = JSON.parse(products)
          var col = [];
          for (var i = 0; i < products.length; i++) {
            for (var key in products[i]) {
              if (col.indexOf(key) === -1) {
                col.push(key);
              }
            }
          }
          ///creating a table to load data-- start
          var table = document.createElement("table");
          var tr = table.insertRow(-1);
          for (var i = 0; i < col.length; i++) {
            var th = document.createElement("th");
            th.innerHTML = col[i];
            tr.appendChild(th);
          }
          for (var i = 0; i < products.length; i++) {
            tr = table.insertRow(-1);
            for (var j = 0; j < col.length; j++) {
              var tabCell = tr.insertCell(-1);
              tabCell.innerHTML = products[i][col[j]];
            }
          }
          var finalOutput = document.getElementById("myCart");
          finalOutput.innerHTML = "";
          finalOutput.appendChild(table);
          ///creating a table to load data-- end
        }
      </script>
    </body>
    
    </html>