MSAL setActiveAccount from within function
02:20 13 Jul 2021

So I'm in the process of setting up MSAL with AAD for my react project. As it is, everything is working as expected, I can login, refresh the page (to get the latest active token) and logout.

However, as I was trying to refactor some of my code to make it more readable, I ran into a problem with setActiveState(), the following code works in my App.js:

export const msalInstance = new PublicClientApplication(msalConfig);
const accounts = msalInstance.getAllAccounts();
if (accounts.length > 0) {
  msalInstance.setActiveAccount(accounts[0]);
} 

However, I wanted to refactor the above as follows - To handle more cases in a joint function:

export const msalInstance = new PublicClientApplication(msalConfig);
function handleResponse(response) {
  if (response !== null) {
    const accountId = response.account.homeAccountId;
  } else {
    const currentAccounts = msalInstance.getAllAccounts();
    if (currentAccounts.length === 0) {
      // no accounts signed-in, attempt to sign a user in
      instance.loginRedirect(loginRequest);
    } else if (currentAccounts.length > 0) {
      msalInstance.setActiveAccount(currentAccounts[0]);
    }
  }
}

msalInstance.handleRedirectPromise().then(handleResponse);

The above code is capable of getting all current accounts and it successfully reaches setActiveAccount, however nothing happens - I.e. my active account is not being set, which means that my is stuck loading.

reactjs azure-active-directory azure-ad-msal