javascriptreactjsformsreact-final-formfinal-form

How to set a form as "pristine" after submit was successful in React Final Form


As a developer I would like to disable the "Submit" button when the user successfully submitted the form using React Final Form, and enable the "Submit" button if the user enters some new text in the form.

Current

The variable pristine sets the disable prop to true only when the form loads for first time, but when the user submit the form (not reloading the page) the variable pristine is false and I expect it to be true in order to disable the "Submit" button.

Desired behaviour

Example of current behaviour

https://codesandbox.io/s/github/final-form/react-final-form/tree/master/examples/simple

My investigation

I tried to use a combination of the following variables provided by Final Form but with unsuccessful results pristine, touched, submitSucceeded, lastSubmittedValues


Solution

  • To accomplish this, you will need to "reinitialize" the form after you submit.

    After your submit is successful, you will need to pass those submitted form values back into the initialValues prop on <Form/>. That will ensure that your pristine value accurately reflects the values that have been saved/submitted.

    If you do this, pristine should be the only value your submit button needs to know if it should be disabled or not.


    Side note: Please only implement this pattern on forms that are editing existing data. The reason being that if you are starting with an empty form, and have required fields, attempting to submit is helpful in that it will mark all the fields as touched so you can display error messages. But if you disable the submit button on pristine, you cannot get this benefit.