Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formik: Why setTimeOut in onSubmit?

I'm new to Formik React Forms lib. I'm wondering why I need to wrap onSubmit code in a setTimeOut:

Example from web site (https://jaredpalmer.com/formik/docs/api/formik#onsubmit-values-values-formikbag-formikbag-gt-void-promise)

<Formik
    initialValues={{ name: 'jared' }}
    onSubmit={(values, actions) => {
        setTimeout(() => {
        alert(JSON.stringify(values, null, 2));
        actions.setSubmitting(false);
        }, 1000);
    }}
>

I can't find any explanation in the docs. As far as I can read the function can be both sync and async...

https://jaredpalmer.com/formik/docs/api/formik#onsubmit-values-values-formikbag-formikbag-void-promise-any

like image 366
olefrank Avatar asked Dec 10 '19 13:12

olefrank


2 Answers

You don't need to put setTimeout() in onSubmit(). It's just an example in the documentation to probably simulate a common use case of sending the form values as a HTTP request.

like image 200
Ciarán Tobin Avatar answered Oct 29 '22 05:10

Ciarán Tobin


It disables the form button for certain amount of time, in your code it is 1 second.

Same data submitted twice may produce unwanted results, like double withdrawal from a bank account or storing two identical items in a shopping cart of an online store.

Also you will get the same data more than once so you will process this unwanted post requests then you have to deal with cleaning up this mess.

You can either disable the button or redirect the user to another page.

like image 44
Yilmaz Avatar answered Oct 29 '22 04:10

Yilmaz