Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hook Form isSubmitting not being set properly

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?

like image 265
noblerare Avatar asked Mar 03 '26 22:03

noblerare


1 Answers

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>
        </>
    )
}
like image 72
Sivadas Rajan Avatar answered Mar 06 '26 14:03

Sivadas Rajan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!