Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda