-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCurrentUserProvider.tsx
65 lines (57 loc) · 1.78 KB
/
CurrentUserProvider.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { useKeycloak } from '@react-keycloak/web';
import { createContext, ReactNode, useCallback, useEffect, useMemo, useState } from 'react';
import { Loading } from '../components/Core/Loading/Loading';
import { GetLoggedInUserAccount, UserAccount } from '../services/userAccount';
import { useAsyncThrowError } from '../utils/errorHandler';
export type UserContextWithSetter = {
LoggedInUser: UserAccount | null;
loadUser: () => Promise<void>;
};
export const CurrentUserContext = createContext<UserContextWithSetter>({
LoggedInUser: null,
loadUser: async () => {
'Unable to load user';
},
});
function CurrentUserProvider({ children }: Readonly<{ children: ReactNode }>) {
const { keycloak } = useKeycloak();
const [isLoading, setIsLoading] = useState<boolean>(true);
const [LoggedInUser, SetLoggedInUser] = useState<UserAccount | null>(null);
const throwError = useAsyncThrowError();
const loadUser = useCallback(async () => {
setIsLoading(true);
try {
const profile = await keycloak.loadUserProfile();
const { user, isLocked } = await GetLoggedInUserAccount();
SetLoggedInUser({
profile,
user,
isLocked,
});
} catch (e: unknown) {
if (e instanceof Error) throwError(e);
} finally {
setIsLoading(false);
}
}, [keycloak, throwError]);
useEffect(() => {
if (keycloak.token) {
loadUser();
} else {
setIsLoading(false);
}
}, [SetLoggedInUser, loadUser, keycloak.token]);
const userContext = useMemo(
() => ({
LoggedInUser,
loadUser,
}),
[LoggedInUser, loadUser]
);
return (
<CurrentUserContext.Provider value={userContext}>
{isLoading ? <Loading /> : children}
</CurrentUserContext.Provider>
);
}
export { CurrentUserProvider };