msal-browser-react icon indicating copy to clipboard operation
msal-browser-react copied to clipboard

Issue with msal-context.js

Open Artyma93 opened this issue 5 years ago • 7 comments

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?

Artyma93 avatar Aug 03 '20 12:08 Artyma93

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.

eglavin avatar Aug 13 '20 10:08 eglavin

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 avatar Aug 26 '20 07:08 Artyma93

@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.

davidepalazzo avatar Sep 22 '20 09:09 davidepalazzo

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]);

vimanmg avatar Oct 20 '20 12:10 vimanmg

What does it mean if pc.getAllAccounts() is returning an empty array?

euticus avatar Apr 02 '21 01:04 euticus

What about using pc.getActiveAccount()?

jamescgoff avatar Apr 28 '21 15:04 jamescgoff

Azure created an official package for managing MSAL in react, msal-react. It's probably a more inclusive option moving forward.

davidepalazzo avatar Apr 29 '21 08:04 davidepalazzo