-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathUserContext.jsx
More file actions
59 lines (48 loc) · 1.4 KB
/
UserContext.jsx
File metadata and controls
59 lines (48 loc) · 1.4 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
57
58
59
import { createContext, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
const publicPaths = ["/explore", "/blog", "/"];
export const UserContext = createContext();
export const UserProvider = ({ children }) => {
const navigate = useNavigate();
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const location = window.location;
// Validate JWT and fetch user
useEffect(() => {
const token = localStorage.getItem("authToken");
if (!token) {
setUser(null);
setLoading(false);
const currentPath = location.pathname;
if (!publicPaths.includes(currentPath)) {
navigate("/"); // Redirect only if not on a public route
}
return;
}
fetch("http://localhost:4000/api/user/me", {
headers: {
Authorization: `Bearer ${token}`
}
})
.then(res => res.json())
.then(data => {
setUser(data.user);
})
.catch(() => {
setUser(null);
localStorage.removeItem("authToken");
})
.finally(() => setLoading(false));
}, [navigate, location.pathname]);
// Logout function
const logout = () => {
localStorage.removeItem("authToken");
setUser(null);
navigate("/");
};
return (
<UserContext.Provider value={{ user, setUser, loading, logout }}>
{children}
</UserContext.Provider>
);
};