forked from CSFrequency/react-firebase-hooks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
useUpdateUser.ts
95 lines (83 loc) · 2.68 KB
/
useUpdateUser.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
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import {
Auth,
AuthError,
updateEmail as fbUpdateEmail,
updatePassword as fbUpdatePassword,
updateProfile as fbUpdateProfile,
} from 'firebase/auth';
import { useMemo, useState } from 'react';
type Profile = {
displayName?: string | null;
photoURL?: string | null;
};
export type UpdateUserHook<M> = [M, boolean, AuthError | Error | undefined];
export type UpdateEmailHook = UpdateUserHook<(email: string) => Promise<void>>;
export type UpdatePasswordHook = UpdateUserHook<
(password: string) => Promise<void>
>;
export type UpdateProfileHook = UpdateUserHook<
(profile: Profile) => Promise<void>
>;
export const useUpdateEmail = (auth: Auth): UpdateEmailHook => {
const [error, setError] = useState<AuthError>();
const [loading, setLoading] = useState<boolean>(false);
const updateEmail = async (email: string) => {
setLoading(true);
setError(undefined);
try {
if (auth.currentUser) {
await fbUpdateEmail(auth.currentUser, email);
} else {
setError(new Error('No user is logged in') as AuthError);
}
} catch (err) {
setError(err as AuthError);
} finally {
setLoading(false);
}
};
const resArray: UpdateEmailHook = [updateEmail, loading, error];
return useMemo<UpdateEmailHook>(() => resArray, resArray);
};
export const useUpdatePassword = (auth: Auth): UpdatePasswordHook => {
const [error, setError] = useState<AuthError>();
const [loading, setLoading] = useState<boolean>(false);
const updatePassword = async (password: string) => {
setLoading(true);
setError(undefined);
try {
if (auth.currentUser) {
await fbUpdatePassword(auth.currentUser, password);
} else {
setError(new Error('No user is logged in') as AuthError);
}
} catch (err) {
setError(err as AuthError);
} finally {
setLoading(false);
}
};
const resArray: UpdatePasswordHook = [updatePassword, loading, error];
return useMemo<UpdatePasswordHook>(() => resArray, resArray);
};
export const useUpdateProfile = (auth: Auth): UpdateProfileHook => {
const [error, setError] = useState<AuthError>();
const [loading, setLoading] = useState<boolean>(false);
const updateProfile = async (profile: Profile) => {
setLoading(true);
setError(undefined);
try {
if (auth.currentUser) {
await fbUpdateProfile(auth.currentUser, profile);
} else {
setError(new Error('No user is logged in') as AuthError);
}
} catch (err) {
setError(err as AuthError);
} finally {
setLoading(false);
}
};
const resArray: UpdateProfileHook = [updateProfile, loading, error];
return useMemo<UpdateProfileHook>(() => resArray, resArray);
};