I have a fetch
function in my useEffect
that gets some data from the backend, but it sends a JWT token to check for user authorization to retrieve the data.
In case the user is not authorized I want to redirect it to my unauthorized page, but the redirect
function just does not work at all, it does absolutely nothing at all.
This is what my useEffect
looks like:
useEffect(() => {
const populateData = async () => {
const response = await OS_Service.getAll('user.token');
if (!response) return redirect('/unauthorized')
setAllServiceOrders(response.data);
setFetching(false);
};
populateData();
}, [setAllServiceOrders, user]);
Anyone knows why it is not working?
CodePudding user response:
import { useHistory } from 'react-router-dom
const Comp = () =>{
const history = useHistory()
......
useEffect(() => {
const populateData = async () => {
const response = await OS_Service.getAll('user.token');
if(!response) history.push('/unauthorized')
setAllServiceOrders(response.data);
setFetching(false);
};
populateData();
}, [setAllServiceOrders, user]);
........
return (<>......</>)
}
CodePudding user response:
The redirect
utility function is for use only in Route
loaders and actions. In React components you should use the useNavigate
hook.
Example:
const navigate = useNavigate();
useEffect(() => {
const populateData = async () => {
const response = await OS_Service.getAll('user.token');
if (!response) {
navigate('/unauthorized', { replace: true });
return;
}
setAllServiceOrders(response.data);
setFetching(false);
};
populateData();
}, [setAllServiceOrders, user]);