Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 24 additions & 19 deletions frontend/src/contexts/UserContext.jsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { createContext, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";

const publicPaths = ["/explore", "/blog", "/"];

export const UserContext = createContext();

Check warning on line 6 in frontend/src/contexts/UserContext.jsx

View workflow job for this annotation

GitHub Actions / eslint

Fast refresh only works when a file only exports components. Move your React context(s) to a separate file

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(() => {
Expand All @@ -15,29 +18,31 @@
if (!token) {
setUser(null);
setLoading(false);
// navigate("/");

const currentPath = location.pathname;

if (!publicPaths.includes(currentPath)) {
navigate("/"); // Redirect only if not on a public route
}

return;
}

if (token) {
fetch("http://localhost:4000/api/user/me", {
headers: {
Authorization: `Bearer ${token}`
}
fetch("http://localhost:4000/api/user/me", {
headers: {
Authorization: `Bearer ${token}`
}
})
.then(res => res.json())
.then(data => {
setUser(data.user);
})
.then(res => res.json())
.then(data => {
setUser(data.user);
})
.catch(() => {
setUser(null);
localStorage.removeItem("authToken");
})
.finally(() => setLoading(false));
} else {
setLoading(false);
}
}, [navigate]);
.catch(() => {
setUser(null);
localStorage.removeItem("authToken");
})
.finally(() => setLoading(false));
}, [navigate, location.pathname]);

// Logout function
const logout = () => {
Expand Down
Loading