feat: time ou

This commit is contained in:
karishmas6
2024-09-25 16:26:09 +05:30
parent aa72538e88
commit 5911fda391

View File

@@ -8,37 +8,58 @@ interface UserRouteProps {
} }
const UserRoute: React.FC<UserRouteProps> = ({ children }) => { const UserRoute: React.FC<UserRouteProps> = ({ children }) => {
const [ok, setOk] = useState<boolean>(true); // Default to true to allow rendering while fetching const [ok, setOk] = useState<boolean>(false);
const [loading, setLoading] = useState<boolean>(true);
const navigate = useNavigate(); const navigate = useNavigate();
const { notify } = useGlobalInfoStore(); const { notify } = useGlobalInfoStore();
useEffect(() => { 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(); fetchUser();
return () => {
controller.abort();
clearTimeout(timeoutId);
};
}, []); }, []);
const fetchUser = async () => { const handleRedirect = (errorMessage: string) => {
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) => {
setOk(false); setOk(false);
if (errorMessage) { setLoading(false);
notify('error', errorMessage); notify('error', errorMessage);
}
navigate('/login'); navigate('/login');
}; };
// If ok is true, render the children (protected route) if (loading) {
return <>{ok ? children : null}</>; return <div>Loading...</div>;
}
return ok ? <>{children}</> : null;
}; };
export default UserRoute; export default UserRoute;