import { useCallback, useEffect, useState } from "react"; import axios from "axios"; import { Outlet, useLocation, useNavigate } from "react-router-dom"; import StatsStyling from "../styles/stats_styling"; const API_BASE_URL = import.meta.env.VITE_BACKEND_URL; type ProfileResponse = { user?: Record; }; const styles = StatsStyling; const getUserLabel = (user: Record | null) => { if (!user) { return "Signed in"; } const username = user.username; if (typeof username === "string" && username.length > 0) { return username; } const email = user.email; if (typeof email === "string" && email.length > 0) { return email; } return "Signed in"; }; const AppLayout = () => { const location = useLocation(); const navigate = useNavigate(); const [isSignedIn, setIsSignedIn] = useState(false); const [currentUser, setCurrentUser] = useState | null>(null); const syncAuthState = useCallback(async () => { const token = localStorage.getItem("access_token"); if (!token) { setIsSignedIn(false); setCurrentUser(null); delete axios.defaults.headers.common.Authorization; return; } axios.defaults.headers.common.Authorization = `Bearer ${token}`; try { const response = await axios.get( `${API_BASE_URL}/profile`, ); setIsSignedIn(true); setCurrentUser(response.data.user ?? null); } catch { localStorage.removeItem("access_token"); delete axios.defaults.headers.common.Authorization; setIsSignedIn(false); setCurrentUser(null); } }, []); useEffect(() => { void syncAuthState(); }, [location.pathname, syncAuthState]); const onAuthButtonClick = () => { if (isSignedIn) { localStorage.removeItem("access_token"); delete axios.defaults.headers.common.Authorization; setIsSignedIn(false); setCurrentUser(null); navigate("/login", { replace: true }); return; } navigate("/login"); }; return (
CrossPost Analysis Engine {isSignedIn ? `Signed in: ${getUserLabel(currentUser)}` : "Not signed in"}
{isSignedIn && ( )}
); }; export default AppLayout;