feat(user-settings): use useAsync and return loading status

Signed-off-by: Reinoud Kruithof <2184455+reinoudk@users.noreply.github.com>
This commit is contained in:
Reinoud Kruithof
2021-12-17 11:31:51 +01:00
parent 2a374057f5
commit 375ed38b16
2 changed files with 25 additions and 21 deletions
+1
View File
@@ -119,5 +119,6 @@ export const UserSettingsThemeToggle: () => JSX.Element;
export const useUserProfile: () => {
profile: ProfileInfo;
displayName: string;
loading: boolean;
};
```
@@ -15,35 +15,38 @@
*/
import {
useApi,
alertApiRef,
identityApiRef,
BackstageUserIdentity,
ProfileInfo,
useApi,
} from '@backstage/core-plugin-api';
import { useEffect, useState } from 'react';
import { useEffect } from 'react';
import { useAsync } from 'react-use';
export const useUserProfile = () => {
const identityApi = useApi(identityApiRef);
const alertApi = useApi(alertApiRef);
const [displayName, setDisplayName] = useState<
string | BackstageUserIdentity
>('');
const [profile, setProfile] = useState<ProfileInfo>({});
const getUserProfile = async () => {
const backstageIdentity = await identityApi.getBackstageIdentity();
const profileInfo = await identityApi.getProfileInfo();
const name = profileInfo.displayName ?? backstageIdentity;
setDisplayName(name);
setProfile(profileInfo);
};
const { value, loading, error } = useAsync(async () => {
return {
profile: await identityApi.getProfileInfo(),
identity: await identityApi.getBackstageIdentity(),
};
}, []);
useEffect(() => {
if (!displayName) {
getUserProfile();
if (error) {
alertApi.post({
message: `Failed to load user identity: ${error}`,
severity: "error",
});
}
});
}, [error, alertApi]);
return { profile, displayName };
return {
profile: loading ? {} : value!.profile,
displayName: loading
? ''
: value!.profile.displayName ?? value!.identity.userEntityRef,
loading,
};
};