-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathAuthContext.jsx
More file actions
56 lines (48 loc) · 1.31 KB
/
AuthContext.jsx
File metadata and controls
56 lines (48 loc) · 1.31 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
45
46
47
48
49
50
51
52
53
54
55
56
import { createContext, useContext, useState, useEffect } from "react";
const AuthContext = createContext(null);
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const storedUser = localStorage.getItem("user");
if (storedUser) {
try {
setUser(JSON.parse(storedUser));
} catch (error) {
console.error("Error parsing stored user information:", error);
localStorage.removeItem("user");
}
}
setIsLoading(false);
}, []);
const login = async (username) => {
setIsLoading(true);
try {
const userData = { username: username.trim() };
setUser(userData);
localStorage.setItem("user", JSON.stringify(userData));
return userData;
} finally {
setIsLoading(false);
}
};
const logout = () => {
setUser(null);
localStorage.removeItem("user");
};
const value = {
user,
isLoading,
login,
logout,
isAuthenticated: !!user,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
};