Basically, I need to render a component based on a state that is set asynchronously, by default the state is "false", so the component mounts and throws the return that corresponds to the false option but it does not wait for the premise that updates the state.
export const LayoutValidator=({children})=>{
const [auth,setAuth] = useState(undefined)
const {token} = JSON.parse(localStorage.getItem("loggedUser")||'{}');
fetch(`${urlValue}/api/validate-token`,{
method:"POST",
headers:{
authorization: token,
}
})
.then(ans=>ans.json())
.then(ans=>setAuth(ans.auth))
.catch(err=>console.log(err))
return auth ? children : <Navigate to="/" />
}
How may I set this component to wait for the premise before returning its answer?
fetch()in auseEffecthook, so that it won't run again and again on every render.setAuth(ans.auth)) after the first render anyway because the http request is asynchronous and takes some time. That's why you need to the "loading" state.authbetweenundefined,trueandfalse, or any other trinary logic. Render nothing (null) or a loading indicator in the loading state. (And actually you might want a fourth state for errors, to render a message in the component instead of logging to the console and keeping the display in loading otherwise)