Files
parcer/src/routes/userRoute.tsx

52 lines
1.5 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 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 }) => {
const [loading, setLoading] = useState(true);
const [ok, setOk] = useState<boolean>(false);
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(() => {
fetchUser();
}, []);
2024-09-25 15:42:07 +05:30
2024-09-25 15:43:24 +05:30
const fetchUser = async () => {
try {
2024-09-25 16:00:16 +05:30
const { data } = await axios.get('http://localhost:8080/auth/current-user');
2024-09-25 15:43:24 +05:30
if (data.ok) {
setOk(true);
2024-09-25 16:00:16 +05:30
} else {
2024-09-25 16:05:08 +05:30
handleRedirect();
2024-09-25 15:43:24 +05:30
}
} catch (err: any) {
2024-09-25 16:05:08 +05:30
handleRedirect(err.response?.data?.error || 'An error occurred. Please login again.');
} finally {
setLoading(false); // Remove loading state regardless of success or failure
2024-09-25 15:43:24 +05:30
}
};
2024-09-25 15:42:07 +05:30
2024-09-25 16:05:08 +05:30
const handleRedirect = (errorMessage?: string) => {
setOk(false);
if (errorMessage) {
notify('error', errorMessage);
} else {
notify('error', 'Please login again to continue');
2024-09-25 16:05:08 +05:30
}
navigate('/login');
};
2024-09-25 16:00:16 +05:30
// Block rendering if loading the authentication status
if (loading) return null;
2024-09-25 16:00:16 +05:30
return <>{ok ? children : null}</>;
2024-09-25 15:42:07 +05:30
};
export default UserRoute;