forked from CSFrequency/react-firebase-hooks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseCreateUserWithEmailAndPassword.ts
52 lines (49 loc) · 1.35 KB
/
useCreateUserWithEmailAndPassword.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
import {
Auth,
AuthError,
createUserWithEmailAndPassword as firebaseCreateUserWithEmailAndPassword,
sendEmailVerification,
UserCredential,
} from 'firebase/auth';
import { useMemo, useState } from 'react';
import { CreateUserOptions, EmailAndPasswordActionHook } from './types';
export default (
auth: Auth,
options?: CreateUserOptions
): EmailAndPasswordActionHook => {
const [error, setError] = useState<AuthError>();
const [registeredUser, setRegisteredUser] = useState<UserCredential>();
const [loading, setLoading] = useState<boolean>(false);
const createUserWithEmailAndPassword = async (
email: string,
password: string
) => {
setLoading(true);
setError(undefined);
try {
const user = await firebaseCreateUserWithEmailAndPassword(
auth,
email,
password
);
if (options && options.sendEmailVerification && user.user) {
await sendEmailVerification(
user.user,
options.emailVerificationOptions
);
}
setRegisteredUser(user);
} catch (error) {
setError(error as AuthError);
} finally {
setLoading(false);
}
};
const resArray: EmailAndPasswordActionHook = [
createUserWithEmailAndPassword,
registeredUser,
loading,
error,
];
return useMemo<EmailAndPasswordActionHook>(() => resArray, resArray);
};