When is Formik's "isSubmitting" set back to False?

Viewed 6217

I have a simple Formik form where the Submit method simply outputs to the console. The structure is

// Submit Form: Custom method referenced in Formik
const submitForm = async (formValues) => {
    console.log(JSON.stringify(formValues));
};

<Formik 
    enableReinitialize
    validationSchema={schema}
    onSubmit={ (values) => {
        submitForm(values); // call my custom Submit method above
    }}
    initialValues={initialFormValues}
>
    {
        ({handleSubmit, handleChange, values, touched, errors, isSubmitting}) 
        => (
            <Form onSubmit={handleSubmit}> {/* Form starts here */}
                ...
                <Button type="submit" disabled={isSubmitting}>Search</Button>
            </Form>
       )
     }
   </Formik>

If there are validation errors, the Submit button correctly ends up enabled after clicking. But if there are no validation errors, I output to the console, and Submit stays disabled even though I'm done. At what point is isSubmitting set back to FALSE in this example?

3 Answers

Not at all. Formik doesn't know when your submit is done, so you need to do it yourself. Formik actually passes the setter into your submit handler for exactly that reason.

Change your code to this:

onSubmit={(values, { setSubmitting }) => {
    submitForm(values, setSubmitting);
}}

and then in your submitForm method, call setSubmitting(false) when done, e.g. in a finally block.

Adding to digitalbreeds answer, actually Formik does reset isSubmitting to false, when your onSubmit handler returns a Promise.

See in the docs:

IMPORTANT: If onSubmit is async, then Formik will automatically set isSubmitting to false on your behalf once it has resolved. This means you do NOT need to call formikBag.setSubmitting(false) manually. However, if your onSubmit function is synchronous, then you need to call setSubmitting(false) on your own.

Related