Prevent Formik from clearing form

Viewed 651

I have a Formik form that gets cleared automatically after all fields are validated and the form is submitted. The purpose of this form is to basically register a new user, so it is a pretty lengthy form.

The problem is that sometimes the email a user enters has been used, or some other value gets bounced back from the backend. For a user it is quite annoying if you're asked to fill a form from the beginning just because one value is incorrect.

How can I prevent Formik from clearing this form automatically, or at least wait for the response from the backend, and then clear or retain the values of the form depending on which one was wrong.

My form is structured this way;

<Formik 
 initialValues,
 onSubmit
 validationSchema,
>
 {()=> return (
  <Form>
   <Field />
    //...quite a long form

What can I do in this situation?

2 Answers

Never mind, thanks guys I was shooting myself in the leg. The form wasn't actually clearing, I was forcing a redirect to the same page based on the success/failure of the request. This was causing the form to be reloaded, so all previous values were getting cleared.

Thanks very much @pushparmar

I think you should go this way if validation is computing on the client-side.

Validate your inputs just before submitting the form.

valid ? submitForm() : through error on the wrong field;

Mention your code snippet for better understanding.

Related