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

153
Vistas
Better way to set dynamic names to items in localStorage

Well, I have an item in localStorage named products. This item contains an Array of JSON Objects that contains products details like quantity, unit_price, etc...

Here is the trigger function to add products to table and update the table...

function addProduct() {
  try {
    //Add product to localstorage
    addProductToLocalStorage();
    //Update pre order table (products)
    updateTable();
    showAlert('Product added!', 'success', 'alert');
  } catch (err) {
    console.log(err);
  }
}

This item is assigned when the user wants to add products to an invoice, I use it to calculate subtotal, taxes and total cost values.

Here is where I add the product to products in localStorage

function addProductToLocalStorage() {
  try {
    //Temporary product
    let product = JSON.parse(localStorage.getItem("tempProduct"));
    let item = JSON.parse(localStorage.getItem("products"));
    //Check if the item already exists
    let products = item ? item : [];
    products.push(product);
    localStorage.setItem("products", JSON.stringify(products));
    //Delete item
    localStorage.removeItem("tempProduct");
  } catch (error) {
    console.log(error);
  }
}

tempProduct is an item that contains information about the product the user is adding, this is because I store information about the product from the server that is not printed to the user, is just to make calculations.

The item is cleared when the invoice is created.

function createInvoice(){
...
localStorage.removeItem("products");
}

The problem here is if the user wants to create two or more invoices and add products to the invoices at the same time, the item is going to store the data of both invoices and will make a mess with the values.

I'm thinking maybe setting dynamic names to the item, like a unique token for every 'Create Inovice' window opened will help me with this, but I don't know if there is a better solution. Let me know how would you deal with this.

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