I am running into a problem with my current code. The code below is supposed to grab a JSON response from my backend and set “data” in the useState function to true or false based on the backend’s response. The issue I am having is that when I click on my button to redirect me to the page it must first go through this protected route in my react router. So it will run this script but the value of ‘data’ never changes. However, my console.log will output the correct boolean based on the JSON response sent from the backend. I am confused on how I can actually grab my JSON response on page load and set it to ‘data’ with useEffect? From my understanding, useEffect will only update my useState ‘data’ when the DOM re-renders.
In short, I want data to = true on page render by checking the JSON response from my backend using axios and if it is true I want to be redirected to the outlet.
I appreciate any help thanks.
const useAuth = () => {
const [data, setData] = useState(false);
useEffect(() => {
const fetchAuthData = async () => {
await axios.get('http://localhost:5000/auth')
.then(resp => {
console.log(resp.data)
setData(resp.data);
})
.catch(err => {
console.log(err);
setData(false)
});
};
fetchAuthData()
}, []);
console.log(data)
// Logic to check if backEndResponse is true or false
if (data === true) {
const authorized = { loggedIn: true }
return authorized && authorized.loggedIn;
} else {
const authorized = { loggedIn: false }
return authorized && authorized.loggedIn;
}
};
const ProtectedRoutes = () => {
const isAuth = useAuth();
return isAuth ? <Outlet/> : <Navigate to="/login" />;
}