I have a shopping cart, when a "Add to Cart" button is pressed, It sets the object to the localStorage.
const addToCartCookie = () => {
let cartData = {
id: product._id,
name: product.name,
slug: product.slug,
productPictures: product.productPictures[0].img,
description: "sabdsjbfjsd",
price: product.storePrice,
quantity: itemCount,
};
window.localStorage.setItem("cart", JSON.stringify(cartData));
};
If again "Add to cart" button is pressed, it replaces the previous object. I need to append each object if the product._id does not exists on the "add to cart" button call. If product._id exists (if already product exists), I need to change the quantity(old one's quantity new one's quantity)
CodePudding user response:
First you need your localStorage item as an array, then check for it's existence first, create if not exists, push after parsing the array, then stringify again to save changes.
const itemToAdd = {
id: product._id,
name: product.name,
slug: product.slug,
productPictures: product.productPictures[0].img,
description: "sabdsjbfjsd",
price: product.storePrice,
quantity: itemCount,
};
const addToCartCookie = (cartItem) => {
const cart = window.localStorage.getItem('cart');
if(cart === null) {
window.localStorage.setItem('cart', JSON.stringify([cartItem]));
} else {
const getCurrentCart = window.localStorage.getItem('cart');
const currentCart = JSON.parse(getCurrentCart);
currentCart.push(cartItem);
window.localStorage.setItem('cart', JSON.stringify(currentCart));
}
};
use like this
addToCartCookie(itemToAdd)
CodePudding user response:
Try using this approach.
Make an item_array array.
Every time you add an item to your cart, first push it in the item_array and then set the complete item_array into the localStorage.
Before adding more items to the cart, get the item_array from the localStorage and push the new item into the item_array. Then again push this item_array with new item into the localStorage.
I hope you get the gist, what we're trying to do here.
CodePudding user response:
That is the workflow to put a new product to you localStorage array.
let current = [
{p: "abc", q: 2},
{p: "def", q: 1},
]
let str = JSON.stringify(current);
console.log('store this string in localStorage', str)
console.log("read the string from localstorage");
let arr = JSON.parse(str)
console.log(arr)
let newProduct = {p: "hij", q: 3}
arr.push(newProduct)
console.log(arr)