feat: redirect to login

This commit is contained in:
karishmas6
2024-09-25 16:05:08 +05:30
parent 289fa826cc
commit 1f570c04c3

View File

@@ -8,7 +8,7 @@ interface UserRouteProps {
} }
const UserRoute: React.FC<UserRouteProps> = ({ children }) => { const UserRoute: React.FC<UserRouteProps> = ({ children }) => {
const [ok, setOk] = useState<boolean | null>(null); // Use null to indicate loading state const [ok, setOk] = useState<boolean>(true); // Default to true to allow rendering while fetching
const navigate = useNavigate(); const navigate = useNavigate();
const { notify } = useGlobalInfoStore(); const { notify } = useGlobalInfoStore();
@@ -22,24 +22,24 @@ const UserRoute: React.FC<UserRouteProps> = ({ children }) => {
if (data.ok) { if (data.ok) {
setOk(true); setOk(true);
} else { } else {
setOk(false); handleRedirect();
notify('error', data.error || 'Please login again to continue');
navigate('/login');
} }
} catch (err: any) { } catch (err: any) {
setOk(false); handleRedirect(err.response?.data?.error || 'An error occurred. Please login again.');
notify('error', err.response?.data?.error || 'An error occurred. Please login again.');
navigate('/login');
} }
}; };
// Loading state const handleRedirect = (errorMessage?: string) => {
if (ok === null) { setOk(false);
return <p>Loading...</p>; if (errorMessage) {
} notify('error', errorMessage);
}
navigate('/login');
};
// Render children if authenticated // If ok is true, render the children (protected route)
return <>{ok ? children : null}</>; return <>{ok ? children : null}</>;
}; };
export default UserRoute; export default UserRoute;