Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

156
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!