Home > Mobile >  Save and refresh language preferences stored in localstorage javascript
Save and refresh language preferences stored in localstorage javascript

Time:07-14

Hi i got a bit of the problem trying to implement language switcher/preference

I made a localstorage item for that, but got a problem becuse of reload need.

function lang_displayed_settings() {
  if (localStorage.getItem("language") === "pl") {
    window.location.hash = "#pl"
    location.reload();
  }
}

I tried to do a function on window load to get a item with preferenced language but i cant really make it to be reload automaticly. Or im getting a loop when window is just reloading on load. I need a function which works on hrefs etc.

Now i have no idea what i can change to get it works! Hope someone made it better than me ;d

(code from above is a clear one, before me useless trying)

CodePudding user response:

If the language item in the localstorage is already set to "pl", your code will reload and will find the property set to the same value again and will just keep reloading your page. The solution is to add another if condition to check for the existence of #pl in window.location.hash so you wouldn't have to reload the page when the hash is already set:

function lang_displayed_settings() {
  if (localStorage.getItem("language") === "pl") {
    if (window.location.hash === "#pl") {
      return;
    } else {
      window.location.hash = "#pl";
      return location.reload();
    }
  }
}

If you want the language setting to support many languages, you can load it from the localsorage on the first loading of the page and then run the hashing logic as follows:

window.onload(() => {
    const lang = localStorage.getItem("language")
    if (window.location.hash === `#${lang}`) {
        return;
      } else {
        window.location.hash = `#${lang}`;
        return location.reload();
      }
})

If my answer was helpful an upvote would be appreciated.

  • Related