Ali Zeinalzadeh
Ali Zeinalzadeh

Reputation: 342

How to stop overwriting data in localStorage

I'm trying to save some data in localStorage. but every time I refresh the page new data overwrite on older data and I lost my old data.

function testshod() {
    localStorage.setItem("hash", JSON.stringify(testblockchain));
    document.getElementById("result").innerHTML = 
    localStorage.getItem("hash");
    }

in store my data like this code. it works correctly but when I refresh the page data are gone.
p.s. testblockchain is a class.

Upvotes: 1

Views: 2296

Answers (1)

Manuel Koch
Manuel Koch

Reputation: 361

You should check if there is already a value in localStorage

function testshod() {
    if (!localStorage.getItem("hash")) {
        localStorage.setItem("hash", JSON.stringify(testblockchain));
    }
    document.getElementById("result").innerHTML = localStorage.getItem("hash");
}

If you want to renew the hash after a given time you should also store the last updated time in the localStorage and check that too.

Upvotes: 2

Related Questions