in my React app I am trying to create a protected route such that, if the user is not logged in, they cannot access the homepage; although not included here, when the user logs in correctly, they should be automatically navigated to the homepage. However, this never happens and it seems as if my useState is not actually updating the state.
My server is definitely producing the right response. If the user is logged in, I get a response of {isLoggedIn: true}, and vice versa if not, however the state of res always seems to remain false. Any help would be appreciated since I'm a little lost here.
Protected Routes
import {Outlet, Navigate} from 'react-router-dom';
import { useState, useEffect} from 'react';
import React from 'react';
import axios from 'axios';
const PrivateRoutes = () =>{
let[res, setRes] = useState(false);
useEffect(() => {
const getData = async () => {
const response = await axios.get("http://localhost:3001/auth", {withCredentials: true});
setRes(response.data.isLoggedIn); //if I console log response.data.isLoggedIn here, I get my expected value, but res never seems to update to this
}
getData();
},[])
return(
res ? <Outlet /> : <Navigate to="/login" />
)
}
export default PrivateRoutes;