-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUserContextWrapper.tsx
56 lines (50 loc) · 1.84 KB
/
UserContextWrapper.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
import { type FC, type PropsWithChildren } from 'react';
import { useQuery } from 'react-query';
import UserContext, { emptyUser } from 'components/UserContext';
import { useAuth } from 'react-oidc-context';
import useApi from 'lib/useApi';
/**
* Wrapper to provide authentication info about the current user, such as email or token
*
* @param props
* @param props.children
*/
const UserContextWrapper: FC<PropsWithChildren> = ({ children }) => {
const authentication = useAuth();
const api = useApi(authentication.user?.access_token);
const amIRegistered = useQuery('registered', () => api.users.getSelf(), {
retry: false,
enabled: authentication.isAuthenticated,
});
const amIAdmin = useQuery('is_admin', () => api.users.tryAdmin(), {
retry: false,
enabled: authentication.user != null,
});
const callbacks = {
login: () => authentication.signinRedirect(),
logout: () => authentication.removeUser(),
};
return (
<UserContext.Provider
value={
authentication.isAuthenticated && authentication.user
? {
token: authentication.user.access_token,
email: amIRegistered.data?.data.email,
registered: amIRegistered.isSuccess,
admin: amIAdmin.isSuccess,
loggedIn: true,
loading:
authentication.isLoading ||
amIRegistered.isLoading ||
amIAdmin.isLoading,
...callbacks,
}
: { ...emptyUser, ...callbacks }
}
>
{children}
</UserContext.Provider>
);
};
export default UserContextWrapper;