File size: 693 Bytes
6c4e56e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import { useEffect } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import { useAuth } from '../../../contexts/AuthContext';
import { ROUTES } from '../../../utils/constants';
export const useRequireAuth = (redirectUrl = ROUTES.LOGIN) => {
const { user, isAuthenticated, isLoading } = useAuth();
const history = useHistory();
const location = useLocation();
useEffect(() => {
if (!isLoading && !isAuthenticated) {
history.replace({
pathname: redirectUrl,
state: { from: location.pathname }
});
}
}, [user, isAuthenticated, isLoading, history, location, redirectUrl]);
return { user, isAuthenticated, isLoading };
}; |