feat: handle !user errors

This commit is contained in:
karishmas6
2024-09-25 16:00:16 +05:30
parent ce7291e048
commit 289fa826cc

View File

@@ -8,29 +8,38 @@ interface UserRouteProps {
} }
const UserRoute: React.FC<UserRouteProps> = ({ children }) => { const UserRoute: React.FC<UserRouteProps> = ({ children }) => {
const [ok, setOk] = useState(true); const [ok, setOk] = useState<boolean | null>(null); // Use null to indicate loading state
const navigate = useNavigate(); const navigate = useNavigate();
const { notify } = useGlobalInfoStore(); const { notify } = useGlobalInfoStore();
useEffect(() => { useEffect(() => {
fetchUser(); fetchUser();
}, []); }, []);
const fetchUser = async () => { const fetchUser = async () => {
try { try {
const { data } = await axios.get('/api/current-user'); const { data } = await axios.get('http://localhost:8080/auth/current-user');
if (data.ok) { if (data.ok) {
setOk(true); setOk(true);
} else {
setOk(false);
notify('error', data.error || 'Please login again to continue');
navigate('/login');
} }
} catch (err: any) { } catch (err: any) {
setOk(false); setOk(false);
notify('error', err.message || 'Please login again to continue'); notify('error', err.response?.data?.error || 'An error occurred. Please login again.');
navigate('/'); navigate('/login');
} }
}; };
// Display loading message while fetching user data // Loading state
return <div>{!ok ? <p>Loading...</p> : <>{children}</>}</div>; if (ok === null) {
return <p>Loading...</p>;
}
// Render children if authenticated
return <>{ok ? children : null}</>;
}; };
export default UserRoute; export default UserRoute;