Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

122
Vistas
how to append to a local storage instead of replacing when new object is passed

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)

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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)
about 4 years ago · Juan Pablo Isaza Denunciar

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

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)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda