So this is more of a javascript question than a reactjs question. I am creating a protected route in reactjs. In this, I am fetching the '/checkauth' get request to check the authentication and it correctly returns the response to me. However the problem is that since it is an async function, it takes time to return that value and thus my return statement is executed earlier. This is the code I am having problem with.
const [auth, setAuth] = useState();
const checkAuthentication = async ()=>{
const res = await fetch('/checkauth', {
method : "GET",
credentials: "include",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
});
const data = await res.json();
return res.status===200 ? (data.isAuthenticated) : (false) ;
}
useEffect(async ()=>{
const data = await checkAuthentication();
setAuth(data)
}, []);
return auth ? <Outlet /> : <Navigate to='/signin' />;
Here the auth is always undefined and thus it always navigates to signing.