Files
parcer/src/routes/userRoute.tsx

46 lines
1.3 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 }) => {
2024-09-25 16:00:16 +05:30
const [ok, setOk] = useState<boolean | null>(null); // Use null to indicate loading state
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 {
setOk(false);
notify('error', data.error || 'Please login again to continue');
navigate('/login');
2024-09-25 15:43:24 +05:30
}
} catch (err: any) {
setOk(false);
2024-09-25 16:00:16 +05:30
notify('error', err.response?.data?.error || 'An error occurred. Please login again.');
navigate('/login');
2024-09-25 15:43:24 +05:30
}
};
2024-09-25 15:42:07 +05:30
2024-09-25 16:00:16 +05:30
// Loading state
if (ok === null) {
return <p>Loading...</p>;
}
// Render children if authenticated
return <>{ok ? children : null}</>;
2024-09-25 15:42:07 +05:30
};
export default UserRoute;