abaracedo
abaracedo

Reputation: 1454

Variable is null after setting value on FB.api function

I'm trying to get the user locale and keep it on a variable.

function myFunction() {

  var userLocale;

  FB.api(
    "/{userID}",
    function (response) {
      if (response && !response.error) {
        userLocale = response.locale;
      }
    }
  );

}

When i set userLocale with the value that gives me the function, the console.log(userLocale); returns undefined.

myFunction is called after check if the user has access to my app.

Upvotes: 0

Views: 87

Answers (1)

Eric Hydrick
Eric Hydrick

Reputation: 3537

You're probably calling console.log before the callback function that sets the userLocale variable. The function you passed into FB.api() won't get called until Facebook responds. Your code to verify userLocale has a value should look like:

function myFunction() {

  var userLocale;

  FB.api(
    "/{userID}",
    function (response) {
      if (response && !response.error) {
        userLocale = response.locale;
        // Wait until I get an FB response before printing userLocale.
        console.log(userLocale);
        // Anything that requires userLocale goes here, not outside the FB.api() call.
      }
    }
  );

}

Upvotes: 2

Related Questions