I am building an spfx webpart using react to fetch users data in my organization using microsoft graph api below is my code, after making the call an checking the dev console i get this error
Error fetching user data: Error: No user account
My code:
public getEmp = async (): Promise<void> => {
try {
const accounts = msalInstance.getAllAccounts();
if (accounts.length === 0) {
throw new Error("No user account found");
}
const activeAccount = accounts[0];
const request = {
scopes: ["User.Read"],
account: activeAccount,
};
// msalInstance.setActiveAccount(msalInstance.getActiveAccount());
const response: AuthenticationResult =
await msalInstance.acquireTokenSilent(request);
const accessToken: string = response.accessToken;
const graphApiResponse = await axios.get(
"https://graph.microsoft.com/v1.0/users",
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
if (graphApiResponse.status !== 200) {
throw new Error(
`Graph API request failed: ${graphApiResponse.statusText}`
);
}
const userData = await graphApiResponse.data;
console.log("User data:", userData);
} catch (error) {
console.error("Error fetching user data:", error);
}
};
Please what am i doing wrong? and if there is another away of going about it kindly let me know.
Fetch all users in my organization data
I had the same issue and mine was solved with below code.