I have a function runValidation that loops through a bunch of numbers and does some calculations. It's might take a while, so I wanted to include an "isLoading" useState.
So I made a simple
const [isLoading, setIsLoading] = useState(false)
When I click a button, I wanna set isLoading to true, run my function and then afterwards do setIsLoading(false). So I made my validation function async, as well as the button handler
const handleClick = async () => {
setIsLoading(true)
const isValid = await runValidation()
setIsLoading(false)
}
And my button component is a simple
<button onClick={() => handleClick()}>Run Validations</button>
Everytime I try to run this however, the loading isn't being set before the validation function is done. So with a useEffect on the "isLoading" variable. I get console.logs showings that
Running Validations
isLoading: true
isLoading: false
Why is my "isLoading" never true until after the async? And is there a way to make sure? I tried moving the setIsLoading(true) down to the button onClick - I tried having .then() instead of await etc. - But isLoading is only set to true after the async function.
EDIT: Example - https://codesandbox.io/s/suspicious-cartwright-0y5jk