-
Notifications
You must be signed in to change notification settings - Fork 302
/
useAuthState.ts
40 lines (34 loc) · 1.01 KB
/
useAuthState.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, onAuthStateChanged, User } from 'firebase/auth';
import { useEffect } from 'react';
import { LoadingHook, useLoadingValue } from '../util';
export type AuthStateHook = LoadingHook<User | null, Error>;
type AuthStateOptions = {
onUserChanged?: (user: User | null) => Promise<void>;
};
export default (auth: Auth, options?: AuthStateOptions): AuthStateHook => {
const { error, loading, setError, setValue, value } = useLoadingValue<
User | null,
Error
>(() => auth.currentUser);
useEffect(() => {
const listener = onAuthStateChanged(
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];
};