Spaces:
Sleeping
Sleeping
File size: 1,181 Bytes
149698e | 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 | import { useEffect } from 'react';
import { Outlet, useNavigate } from 'react-router';
import Sidebar from './Sidebar';
import { useAuthStore } from '@/stores/authStore';
export default function MainLayout() {
const user = useAuthStore((s) => s.user);
const navigate = useNavigate();
// Eagerly fetch user profile on mount if not already in store
useEffect(() => {
if (user) return;
let cancelled = false;
async function init() {
try {
const res = await fetch('/api/auth/me', { credentials: 'include' });
if (res.ok && !cancelled) {
const { user: userData } = await res.json();
useAuthStore.getState().setUser(userData);
} else if (!cancelled) {
// Not authenticated — redirect to login
navigate('/login');
}
} catch {
if (!cancelled) navigate('/login');
}
}
init();
return () => { cancelled = true; };
}, [user, navigate]);
return (
<div className="flex h-screen w-full overflow-hidden">
<Sidebar />
<main className="flex flex-1 flex-col overflow-hidden bg-background">
<Outlet />
</main>
</div>
);
}
|