Issue with msal-context.js
Issue with msal-context.js file encountered on startup
TypeError: pc.getAccount is not a function (anonymous function) D:/JS/React/Download/6 pcibraro_msal-browser-react/msal-browser-react-master/src/msal-context.js:45 42 | setLoginError(error); 43 | }); 44 |
45 | if (pc.getAccount()) { 46 | ^ setUser(pc.getAccount()); 47 | setIsAuthenticated(true); 48 | }
What could be the reason for this problem?
Seems to be a problem with the getAccount function used in the msal-context.js file, I replaced that function with getAccountByUsername and it seems to work now.
Must have been a change in a recent update on the @azure/msal-browser package.
The project started, but after passing the authentication (when you click on the "Log in" button) the following error is received: TypeError: Cannot read property 'userName' of null Welcome D:/JS/React/Download/1 pcibraro_msal-browser-react/msal-browser-react-master/src/Welcome.js:10
7 |
8 | return (
9 | <div>
10 | <h1>Welcome {user.userName}</h1>
11 | {token && (<span>Your token is {token}</span>)}
12 | <br></br>
13 | <button onClick={() => getToken(apiRequest, "loginPopup")}>Get Token</button>
@Artyma93 that's because the account info returns a user.username. I found that in MSAL docs.
@eglavin yes. It seems that the correct way is to call getAllAccounts() and then handle the case for single and multiple accounts. Sadly, their docs doesn't have a working example for multiple accounts.
I fixed it by replacing pc.getAccount() for pc.getAllAccounts() and then assigning its first value to user's info:
const accounts = pc.getAllAccounts(); setUser(accounts[0]);
What does it mean if pc.getAllAccounts() is returning an empty array?
What about using pc.getActiveAccount()?
Azure created an official package for managing MSAL in react, msal-react. It's probably a more inclusive option moving forward.