This is my react code for Protected Route:
import React, { useState } from "react";
import { Navigate, Route } from "react-router-dom";
const ProtectedRoute = (props) => {
const [isAuthenticated, setisAuthenticated] = useState(false);
const checkALog = async () => {
const response = await fetch("http://localhost:3000/checkAuth", {
credentials: "include",
});
const data = await response.json();
console.log("Response from server:", data);
if (data.message === "authenticated") {
setisAuthenticated(true);
} else {
setisAuthenticated(false);
}
}
checkALog();
console.log(isAuthenticated);
return isAuthenticated ? <Route {...props} /> : <Navigate to="/" />;
};
export default ProtectedRoute;
I am getting false as the console message when i did console.log(isAuthenticated);
. And the backend is properly giving the message in data as "authenticated".
Any suggestions? How can I fix this?
Tried to ask chatgpt but it didn’t help me.
2
Answers
useState doesn’t change the direct value. In react every state is changes when there is any event performed. but there is not event call you have just called you function.
you could achieve this without useState.
The good practice always is to use useEffect hook whenever you are making any async calls or fetches. Try calling your function checkALog() inside the useEffect hook.