I have a counter of clicks. Every click increase value. I'd like to save to in local storage, that refreshing page keeps the value. Now it saves the value in local storage, but not keep it if I refresh the browser. What should I change in my code to make it work properly?
let countedClicks = 0;
const countingClicks = () => {
countedClicks += 1;
localStorage.setItem("btnClicksSaved", countedClicks);
let savedClicks = localStorage.getItem("btnClicksSaved");
clicks.innerHTML = `${savedClicks} times`;
console.log(countedClicks + "counted");
console.log(savedClicks + "local storage");
if (savedClicks > 5) {
resetBtn.style.display = "flex";
} else {
resetBtn.style.display = "none";
}
};
You should get data first otherwise it will always start with 0.
let countedClicks = parseInt(localStorage.getItem("btnClicksSaved") ?? '0');
const countingClicks = () => {
countedClicks += 1;
localStorage.setItem("btnClicksSaved", countedClicks);
let savedClicks = localStorage.getItem("btnClicksSaved");
clicks.innerHTML = `${savedClicks} times`;
console.log(countedClicks + "counted");
console.log(savedClicks + "local storage");
if (savedClicks > 5) {
resetBtn.style.display = "flex";
} else {
resetBtn.style.display = "none";
}
};
Because you're reading the counting clicks from the memory (using the variable countedClicks). You should read it from the local storage directly instead. variables values will get lost after refreshing the page because they get saved in the memory, on the other hand, local storage data gets saved into the disk.
const countingClicks = () => {
let savedClicks = localStorage.getItem("btnClicksSaved");
if (savedClicks === null) {
localStorage.setItem("btnClicksSaved", 0);
savedClicks = localStorage.getItem("btnClicksSaved");
}
const countedClicks = parseInt(savedClicks) + 1;
localStorage.setItem("btnClicksSaved", countedClicks);
savedClicks = localStorage.getItem("btnClicksSaved");
clicks.innerHTML = `${savedClicks} times`;
console.log(countedClicks + "counted");
console.log(savedClicks + "local storage");
if (savedClicks > 5) {
resetBtn.style.display = "flex";
} else {
resetBtn.style.display = "none";
}
};
try this
/* load value from localStorage first */
let countedClicks = localStorage.getItem("btnClicksSaved");
/* there's no "btnClicksSaved" in localStorage
* when you visited the site for the first time, so set the value to "0" */
if (countedClicks != null) { return } else { countedClicks = 0 }
const countingClicks = () => {
/* no need to change anything here */
}