Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

localstorage item value resetting

I have javascript code below

let beer_JSON = {"name": "beer", "price": 2.99, "quantity": 0};

let beer = document.getElementById("beer");

function alert(){
    Swal.fire({
         position: 'top-end',
         icon: 'success',
         title: 'added',
         showConfirmButton: false,
         timer: 1500
       });
 }

    beer.addEventListener("click", function() {
        alert();
        beer_JSON.quantity++;
        localStorage.setItem('beer', JSON.stringify(beer_JSON));
      });

My quantity value resets to 0 after page refreshes. How can I fix that

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This code executes every time page refreshes and resets quantity.

let beer_JSON = {"name": "beer", "price": 2.99, "quantity": 0};

You need to get this initial data from localStorage. Replace the first line with this code.

let beer_JSON = JSON.parse(localStorage.getItem("beer")) || {"name": "beer", "price": 2.99, "quantity": 0};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading