-
Notifications
You must be signed in to change notification settings - Fork 307
/
Copy pathuseIdToken.ts
40 lines (34 loc) · 1019 Bytes
/
useIdToken.ts
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
import { Auth, onIdTokenChanged, User } from 'firebase/auth';
import { useEffect } from 'react';
import { LoadingHook, useLoadingValue } from '../util';
export type IdTokenHook = LoadingHook<User | null, Error>;
type IdTokenOptions = {
onUserChanged?: (user: User | null) => Promise<void>;
};
export default (auth: Auth, options?: IdTokenOptions): IdTokenHook => {
const { error, loading, setError, setValue, value } = useLoadingValue<
User | null,
Error
>(() => auth.currentUser);
useEffect(() => {
const listener = onIdTokenChanged(
auth,
async (user) => {
if (options?.onUserChanged) {
// onUserChanged function to process custom claims on any other trigger function
try {
await options.onUserChanged(user);
} catch (e) {
setError(e as Error);
}
}
setValue(user);
},
setError
);
return () => {
listener();
};
}, [auth]);
return [value, loading, error];
};