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

vanilla JS localStorage persist data on refresh

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 ?

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 :

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));
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