Reputation: 11903
I have a form in which I am displaying a loading indicator when it is submitting.
However, it appears that the isSubmitting
property seems to be set off and on really quickly and doesn't show the loading indicator at all. I've throttled the network speed to something like "Slow 3G" in Chrome's dev tools and I see my form wait and wait during submission but no loading indicator is shown.
const myForm = () => {
const formMethods = useForm()
const { formState, handleSubmit } = formMethods
const { isSubmitting } = formState
const onSubmit = () => {
// Submit the form
}
return (
<>
{isSubmitting && <LoadingIndicator />}
<form onSubmit={handleSubmit(onSubmit)}>
</form>
</>
)
}
If I add a:
useEffect(() => {
console.log(isSubmitting)
}, [isSubmitting])
I see the following printed out almost instantaneously while the form still waits for a low network submission to occur.
true
false
How do I get React Hook Form to properly show the loading indicator?
Upvotes: 3
Views: 1960
Reputation: 987
What you need to do is to return a promise on the onsubmit function. otherwise there is no way to track if the form is submitting or not. You may not need to create a new promise always
const myForm = () => {
const formMethods = useForm()
const { formState, handleSubmit } = formMethods
const { isSubmitting } = formState
const onSubmit = () => {
return new Promise((resolve:any,reject:any)=>{
// Submit the form
if(result == 'OK'){
resolve()
}else{
reject()
}
});
}
return (
<>
{isSubmitting && <LoadingIndicator />}
<form onSubmit={handleSubmit(onSubmit)}>
</form>
</>
)
}
Upvotes: 3
Reputation: 2848
If you are submitting the form details to API call then you can use useState
and update it in api call. check e.g. below.
const formMethods = useForm()
const { formState, handleSubmit } = formMethods
const { isSubmitting } = formState
const [isLoading, setIsLoading] = React.useState;
const onSubmit = () => {
setIsLoading(true)
YOUR_API_CALL
.then((res) => {
setIsLoading(false)
})
.catch((err) => {
setIsLoading(false)
})
}
return (
<>
{isLoading
? <LoadingIndicator />
: (
<form onSubmit={handleSubmit(onSubmit)}>
</form>
)}
</>
)
}
Upvotes: 1