I am trying to build a protected route so that when a non-authenticated user tries to access certain components they will be redirected to the login page. The issue is that when a user is logged in, and I refresh the page, the "if" statement runs before my useEffect triggers and updates redux state, thus it always redirects a logged in user back to the login page on page refresh, when it should just authenticate the user and stay on that page. I cannot seem to figure out a way around this. Any help would be appreciated
export const ProtectedRoute = ({children}) => {
const user = useSelector((state) => state.user)
const [loaded, setLoaded] = useState(false);
const navigate = useNavigate();
const dispatch = useDispatch();
useEffect(() => {
dispatch(restoreUser()).then(() => setLoaded(true))
}, []);
if(loaded){
if(user.user?.error){
return navigate('/login');
}
}
return children;
}