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
CodePudding user response:
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};