feat: use user from context
This commit is contained in:
@@ -1,58 +1,12 @@
|
|||||||
import { useState, useEffect, ReactNode } from 'react';
|
import React from 'react';
|
||||||
import axios from 'axios';
|
import { Navigate, Outlet } from 'react-router-dom';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useContext } from 'react';
|
||||||
import { useGlobalInfoStore } from "../context/globalInfo";
|
import { AuthContext } from '../context/auth';
|
||||||
import { CircularProgress } from '@mui/material';
|
|
||||||
|
|
||||||
interface UserRouteProps {
|
const UserRoute = () => {
|
||||||
children: ReactNode;
|
const { state } = useContext(AuthContext);
|
||||||
}
|
|
||||||
|
|
||||||
const UserRoute: React.FC<UserRouteProps> = ({ children }) => {
|
return state.user ? <Outlet /> : <Navigate to="/login" />;
|
||||||
const [ok, setOk] = useState<boolean>(false);
|
|
||||||
const [loading, setLoading] = useState<boolean>(true);
|
|
||||||
const navigate = useNavigate();
|
|
||||||
const { notify } = useGlobalInfoStore();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const fetchUser = async () => {
|
|
||||||
try {
|
|
||||||
const { data } = await axios.get('http://localhost:8080/auth/current-user');
|
|
||||||
if (data.ok) {
|
|
||||||
setOk(true);
|
|
||||||
} else {
|
|
||||||
handleRedirect('User session expired. Please login again.');
|
|
||||||
}
|
|
||||||
} catch (err: any) {
|
|
||||||
if (axios.isCancel(err)) {
|
|
||||||
console.log('Request canceled:', err.message);
|
|
||||||
handleRedirect('Request timed out. Please try again.');
|
|
||||||
} else {
|
|
||||||
handleRedirect();
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
fetchUser();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleRedirect = (errorMessage?: string) => {
|
|
||||||
setOk(false);
|
|
||||||
setLoading(false);
|
|
||||||
if (errorMessage) {
|
|
||||||
notify('error', errorMessage);
|
|
||||||
}
|
|
||||||
navigate('/login');
|
|
||||||
};
|
|
||||||
|
|
||||||
if (loading) {
|
|
||||||
return <div><CircularProgress /></div>;
|
|
||||||
}
|
|
||||||
|
|
||||||
return ok ? <>{children}</> : null;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export default UserRoute;
|
export default UserRoute;
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user