diff --git a/src/routes/userRoute.tsx b/src/routes/userRoute.tsx index 711f9e31..d53f36cb 100644 --- a/src/routes/userRoute.tsx +++ b/src/routes/userRoute.tsx @@ -8,37 +8,58 @@ interface UserRouteProps { } const UserRoute: React.FC = ({ children }) => { - const [ok, setOk] = useState(true); // Default to true to allow rendering while fetching + const [ok, setOk] = useState(false); + const [loading, setLoading] = useState(true); const navigate = useNavigate(); const { notify } = useGlobalInfoStore(); useEffect(() => { + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 second timeout + + const fetchUser = async () => { + try { + const { data } = await axios.get('http://localhost:8080/auth/current-user', { + signal: controller.signal + }); + if (data.ok) { + setOk(true); + } else { + handleRedirect('User session expired. Please login again.'); + } + } catch (err: any) { + if (axios.isCancel(err)) { + console.log('Request canceled:', err.message); + handleRedirect('Request timed out. Please try again.'); + } else { + handleRedirect(err.response?.data?.error || 'An error occurred. Please login again.'); + } + } finally { + setLoading(false); + clearTimeout(timeoutId); + } + }; + fetchUser(); + + return () => { + controller.abort(); + clearTimeout(timeoutId); + }; }, []); - const fetchUser = async () => { - try { - const { data } = await axios.get('http://localhost:8080/auth/current-user'); - if (data.ok) { - setOk(true); - } else { - handleRedirect(); - } - } catch (err: any) { - handleRedirect(err.response?.data?.error || 'An error occurred. Please login again.'); - } - }; - - const handleRedirect = (errorMessage?: string) => { + const handleRedirect = (errorMessage: string) => { setOk(false); - if (errorMessage) { - notify('error', errorMessage); - } + setLoading(false); + notify('error', errorMessage); navigate('/login'); }; - // If ok is true, render the children (protected route) - return <>{ok ? children : null}; + if (loading) { + return
Loading...
; + } + + return ok ? <>{children} : null; }; export default UserRoute;