Bich Le The
Bich Le The

Reputation: 57

Added duplicate data are ovewritten in LocalStorage

So I have this function addToCart in Javascript where by clicking on a button the name of the item and Amount is saved to LocalStorage and then I get the data with innerHTML. The problem here is that whenever I click twice or more times on that button the data overwrites.

For example I want to add one doll to cart, then I want to add another two dolls, then saved is only>

Doll:2

but i want it to be

Doll:1
Doll:2

My code:

const lookUpItem = matches.map((match, idx)=>
    `<h2 id="name"><span id="${match.itemName}">${match.itemName}</span></h2>
     <p>Amount: <span id="am_${idx}">${match.amount1}</span></p>
     <button onclick="addToCart('${match.itemName}', 'am_${idx}')" id="add">Add to Cart</button>
                    </span></small>
            </div>`
        ).join('');
        itemList.innerHTML = lookUpItem;

//outPut is id of an <ul> in HTML
const outPutHTML = document.getElementById("outPut");

//nm, am - variables from array.map
//saves line to localStorage and adds line to outputHTML
function addToCart(nm, am) {
    {
        const itemName = nm;
        const amount = document.getElementById(am).innerText;
        localStorage.setItem(itemName, amount);
        outPutHTML.innerHTML += `${itemName}: ${amount}<br />`;
    }
}

//shows all data in Local Storage in outPutHTML
for(let i = 0; i < localStorage.length; i++) {
    const name = localStorage.key(i);
    const value = localStorage.getItem(name);
    outPutHTML.innerHTML += `${name}: ${value} <br />`;
}

How to solve this, I saw that you could solve this with JSON.stringtify, but don't exactly know how to apply it? I appreciate the help.

Upvotes: 1

Views: 825

Answers (1)

trincot
trincot

Reputation: 350272

You cannot store two items with the same key in local storage.

It is better to first think how you would store it in memory -- without the locale storage in mind.

For instance, you could imagine this structure:

items = [
    { name: "Doll", value: "1" },
    { name: "Doll", value: "2" }
];

And if you need to add another, you just do

items.push({ name: "Doll", value: "15" });

And once you have your memory structure defined, you can just write that whole structure to local storage, using one, hard-coded key:

localStorage.setItem("items", JSON.stringify(items));

And to read that information at the start of your page:

items = JSON.parse(localStorage.getItem("items") || "[]");

The || is there to treat the case where the data is not yet present in local storage, in which case you want to get an empty array.

So here is part of your code adapted. The comments are your comments, so you can see where the code fits in:

//shows all data in Local Storage in outPutHTML
const items = JSON.parse(localStorage.getItem("items") || "[]");
outPutHTML.innerHTML = items.map(({name, value}) => `${name}: ${value}<br>`)
                            .join("");

//saves line to localStorage and adds line to outputHTML
function addToCart(name, am) {
    const value = document.getElementById(am).innerText;
    items.push({name, value});
    localStorage.setItem("items", JSON.stringify(items));
    outPutHTML.innerHTML += `${name}: ${value}<br>`;
}

Upvotes: 1

Related Questions