I'm using vanilla JS and I want to persist data on localStorage
when page refreshes:
main.js
localStorage.setItem("language", "ar");
const toEnglish = (e) => {
if (e.target.closest(".english")) {
localStorage.setItem("language", "en");
}
};
document.addEventListener("click", (e) => toEnglish(e));
however, after setting language
to en
on localStorage
, if the page refreshes the value resets to ar
, i wonder why it doesn't persist the value like in reactJS
?
It happen because every page load you change language to ar
You need to check is language already set
if (!localStorage.getItem("language")) {
localStorage.setItem("language", "ar");
}
const toEnglish = (e) => {
if (e.target.closest(".english")) {
localStorage.setItem("language", "en");
}
};
document.addEventListener("click", (e) => toEnglish(e));