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 15:43:24 +05:30
|
|
|
const [ok, setOk] = useState(true);
|
|
|
|
|
const navigate = useNavigate();
|
2024-09-25 15:42:07 +05:30
|
|
|
|
2024-09-25 15:43:24 +05:30
|
|
|
const { notify } = useGlobalInfoStore();
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
fetchUser();
|
|
|
|
|
}, []);
|
2024-09-25 15:42:07 +05:30
|
|
|
|
2024-09-25 15:43:24 +05:30
|
|
|
const fetchUser = async () => {
|
|
|
|
|
try {
|
|
|
|
|
const { data } = await axios.get('/api/current-user');
|
|
|
|
|
if (data.ok) {
|
|
|
|
|
setOk(true);
|
|
|
|
|
}
|
|
|
|
|
} catch (err: any) {
|
|
|
|
|
setOk(false);
|
|
|
|
|
notify('error', err.message || 'Please login again to continue');
|
|
|
|
|
navigate('/');
|
|
|
|
|
}
|
|
|
|
|
};
|
2024-09-25 15:42:07 +05:30
|
|
|
|
2024-09-25 15:43:24 +05:30
|
|
|
// Display loading message while fetching user data
|
|
|
|
|
return <div>{!ok ? <p>Loading...</p> : <>{children}</>}</div>;
|
2024-09-25 15:42:07 +05:30
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export default UserRoute;
|