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);
}

