Javascript Variable not updating/saving

Viewed 1822

I have a string which I need in multiple functions. Therefore I want to save it in a variable.
But when I try to assign it inside a function it doesn't update the variable.

var auth_code = "na";
function safeAuthCode(authcode){
  auth_code = authcode;
  console.log(auth_code);
}

"auth_code" prints just fine in the console at that point, but when I try to use it later it just contains "na".
Not sure what I'm doing wrong tbh :/

Edit:

This is the function in which safeAuthCode is called:

function auth(){
  chrome.identity.launchWebAuthFlow({
    "url": "https://accounts.spotify.com/authorize?client_id="+client_id+
    "&redirect_uri="+ encodeURIComponent(redirectUri) +
    "&response_type=code"+
    "&scope=" + encodeURIComponent(scopes),
    "interactive": true
  },
  function(redirect_url) {
    var url = new URL(redirect_url);
    var code = url.searchParams.get("code");
    safeAuthCode(code);
  });
}
2 Answers

I am assuming that the problem you are having is because of the global variable that either gets overwritten in a different part of the code, or because your code at a certain point in time reloads, and the initial value gets reset.

To save such authentication code, you could make use of the sessionStorage object of your browser.

To make sure you only have 1 such object, you could use the const keyword to define your variables (in case another definition of that variable would come at a later time, you should get an error thrown)

const authorisationSettings = {
  get code() {
    return sessionStorage.getItem('authorisationCode') || 'na';
  },
  set code(value) {
    return sessionStorage.setItem('authorisationCode');
  }
};

function saveAuthorisationCode( code ) {
  authorisationSettings.code = code;
}

saveAuthorisationCode( 'test' );
console.log( authorisationSettings.code );

This snippet doesn't work on stackoverflow, so you can find the jsfiddle here

It happens because of when your function is executed, in lexical environment of that function is already exist authcode variable and you are trying to set this one instead of global authcode

You need to change name of global variable or param of the fuction...

Related