-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathauthContext.js
40 lines (34 loc) · 976 Bytes
/
authContext.js
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
import { createContext, useContext, useState, useEffect } from 'react';
import checkAuth from '@/app/actions/checkAuth';
const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [currentUser, setCurrentUser] = useState(null);
useEffect(() => {
const checkAuthentication = async () => {
const { isAuthenticated, user } = await checkAuth();
setIsAuthenticated(isAuthenticated);
setCurrentUser(user);
};
checkAuthentication();
}, []);
return (
<AuthContext.Provider
value={{
isAuthenticated,
setIsAuthenticated,
currentUser,
setCurrentUser,
}}
>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};