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.