-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthContext.js
More file actions
44 lines (37 loc) · 1.1 KB
/
AuthContext.js
File metadata and controls
44 lines (37 loc) · 1.1 KB
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
import React, { createContext, useState, useContext, useEffect } from 'react';
import { auth } from './firebaseConfig';
import { signInWithEmailAndPassword, signOut as firebaseSignOut, onAuthStateChanged } from 'firebase/auth';
const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
if (user) {
setUser(user);
} else {
setUser(null);
}
});
return () => unsubscribe();
}, []);
const signIn = async (email, password) => {
try {
await signInWithEmailAndPassword(auth, email, password);
} catch (error) {
console.error('Error signing in: ', error);
}
};
const signOut = async () => {
try {
await firebaseSignOut(auth);
} catch (error) {
console.error('Error signing out: ', error);
}
};
return (
<AuthContext.Provider value={{ user, signIn, signOut }}>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => useContext(AuthContext);