Files
parcer/src/routes/userRoute.tsx

70 lines
2.0 KiB
TypeScript
Raw Normal View History

2024-09-25 15:43:10 +05:30
import { useState, useEffect, ReactNode } from 'react';
2024-09-25 15:42:07 +05:30
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import { useGlobalInfoStore } from "../context/globalInfo";
2024-09-25 16:31:53 +05:30
import { CircularProgress } from '@mui/material';
2024-09-25 15:42:07 +05:30
2024-09-25 15:43:10 +05:30
interface UserRouteProps {
2024-09-25 15:43:24 +05:30
children: ReactNode;
2024-09-25 15:43:10 +05:30
}
const UserRoute: React.FC<UserRouteProps> = ({ children }) => {
2024-09-25 16:26:09 +05:30
const [ok, setOk] = useState<boolean>(false);
const [loading, setLoading] = useState<boolean>(true);
2024-09-25 15:43:24 +05:30
const navigate = useNavigate();
const { notify } = useGlobalInfoStore();
2024-09-25 16:00:16 +05:30
2024-09-25 15:43:24 +05:30
useEffect(() => {
2024-09-25 16:26:09 +05:30
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 second timeout
2024-09-25 15:42:07 +05:30
2024-09-25 16:26:09 +05:30
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 {
2024-09-25 16:37:04 +05:30
handleRedirect();
2024-09-25 16:26:09 +05:30
}
} finally {
setLoading(false);
clearTimeout(timeoutId);
2024-09-25 15:43:24 +05:30
}
2024-09-25 16:26:09 +05:30
};
fetchUser();
return () => {
controller.abort();
clearTimeout(timeoutId);
};
}, []);
2024-09-25 15:42:07 +05:30
2024-09-25 16:37:04 +05:30
const handleRedirect = (errorMessage?: string) => {
2024-09-25 16:05:08 +05:30
setOk(false);
2024-09-25 16:26:09 +05:30
setLoading(false);
2024-09-25 16:37:04 +05:30
if (errorMessage) {
notify('error', errorMessage);
}
2024-09-25 16:05:08 +05:30
navigate('/login');
};
2024-09-25 16:00:16 +05:30
2024-09-25 16:26:09 +05:30
if (loading) {
2024-09-25 16:31:53 +05:30
return <div><CircularProgress /></div>;
2024-09-25 16:26:09 +05:30
}
return ok ? <>{children}</> : null;
2024-09-25 15:42:07 +05:30
};
export default UserRoute;
2024-09-25 16:10:28 +05:30