0

I am calling an api to get the user's country language and storing in localStorage for further use. The data it's on localStorage but I'm getting null value on the first call. The data is only retrieved if I call it again. It seems there is a delay, I am not sure if it's because localStorage, I would appreciate an explanation. How can I get the data right on the first call?

    if ((!country_lang) {
        $.getJSON('https://api.ipregistry.co/?key=' + api_ipregistry_key, function(data) {
            localStorage.setItem('country_lang', data.location.language.code);
        });
    }

    var country_lang = localStorage.getItem('country_lang');
    alert(country_lang);
Kelson Batista
  • 406
  • 4
  • 25
  • Is `if ((!country_lang) {` a correct statement? I think it should be `if (!country_lang)`. And, no `localStorage` gets data *instantly*. And, I think your code `setItem` everytime the page loads, that's why it takes time for `localStorage`. – Sally loves Lightning Jul 01 '23 at 01:28
  • @LightningMcQueen Yes it's a correct statement, the data is being recorded in localStorage correctly. I just need to retrieve outside the function. The setItem is called just once, because on the second load I have country_lang so it not enters into "if" condition. – Kelson Batista Jul 01 '23 at 01:31

0 Answers0