-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAuthContext.tsx
63 lines (53 loc) · 1.48 KB
/
AuthContext.tsx
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
"use client";
import { createContext, useContext, useEffect, useState } from "react";
import {
onAuthStateChanged,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signInWithPopup,
signOut,
GoogleAuthProvider,
} from "firebase/auth";
import { auth } from "./config/firebase";
import { useRouter } from "next/navigation";
const AuthContext = createContext<any>({});
export const useAuth = () => useContext(AuthContext);
export const AuthContextProvider = ({
children,
}: {
children: React.ReactNode;
}) => {
const [user, setUser] = useState<any>(null);
const [loading, setLoading] = useState(true);
const router = useRouter();
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
if (user) {
setUser(user);
} else {
setUser(null);
}
setLoading(false);
});
return () => unsubscribe();
}, []);
const signup = (email: string, password: string) => {
return createUserWithEmailAndPassword(auth, email, password);
};
const login = (email: string, password: string) => {
return signInWithEmailAndPassword(auth, email, password);
};
const loging = () => {
const provider = new GoogleAuthProvider();
return signInWithPopup(auth, provider);
};
const logout = async () => {
setUser(null);
await signOut(auth);
};
return (
<AuthContext.Provider value={{ user, login, signup, logout, loging }}>
{loading ? null : children}
</AuthContext.Provider>
);
};