All of the suggested references in the comments help explain what's happening here. But here's a simple explanation of what's happening to help you out (before this gets duped and removed):
function myComponent(props){
const [state, setState] = useState("WAIT")
function run(){
setState("LOAD");
// Yes, state is set to LOAD, albeit briefly.
props.apiFetch();
// fetch is an async api, and therefore non-blocking, i.e the next line of code runs immediately.
setState("WAIT");
// This runs immediately after the first setState, so you never actually see the state being set to LOAD. It just gets set right back to WAIT because Javascript doesn't wait for fetch to finish before moving on.
}
return(<h1 onClick={run}>{state}</h1>)
}
As a side note, you would need to apply the await
to the props.apiFetch()
to get the effect you're looking for, not the setState
call. Although, depending on the speed of the fetch return, you still may not see the state changing on screen.