-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseFirebaseAuth.ts
51 lines (42 loc) · 1.43 KB
/
useFirebaseAuth.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
import { useState, useEffect } from "react";
import auth from "@react-native-firebase/auth";
import * as EmailValidator from "email-validator";
import { useProxy } from "valtio/utils";
import { userProxy } from "./proxies";
export const useFirebaseAuth = () => {
const [initializing, setInitializing] = useState(true);
const userState = useProxy(userProxy);
// Handle user state changes
const onAuthStateChanged = (user) => {
if (user === null) {
userState.user.uid = null;
return;
}
userState.user.uid = user?.uid;
if (initializing) setInitializing(false);
};
useEffect(() => {
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
return subscriber; // unsubscribe on unmount
}, []);
return { initializing };
};
export const createUserByEmailAndPassword = async (
email: string,
password: string
) => {
const isValidEmail = EmailValidator.validate(email);
const isValidPassword = password?.length >= 8;
if (isValidEmail && isValidPassword) {
return auth().createUserWithEmailAndPassword(email, password);
}
return { isValidEmail, isValidPassword };
};
export const signIn = (email: string, password: string) => {
const isValidEmail = EmailValidator.validate(email);
const isValidPassword = password?.length >= 8;
if (isValidEmail && isValidPassword) {
return auth().signInWithEmailAndPassword(email, password);
}
return { isValidEmail, isValidPassword };
};