Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hook Form - Resetting "isDirty" without clearing form?

Basically what the title says. When I submit the form I'm checking if the login is successful, if not it displays a message. However, when the user starts to type I want this message to go away.

Kinda assumed isDirty would be cleared once the form was submitted, but it remains dirty. I can call reset from the onSubmit, but that will clear the forms' content - which I don't want.

Ideas?

like image 981
Ills Avatar asked Sep 18 '20 09:09

Ills


People also ask

How do I reset my react hook form data?

The solution is to use the reset() function from the React Hook Form library, if you execute the function without any parameters ( reset() ) the form is reset to its default values, if you pass an object to the function it will set the form with the values from the object (e.g. reset({ firstName: 'Bob' }) ).

How do you reset form after submit in react?

To clear input values after form submit in React: Store the values of the input fields in state variables. Set the onSubmit prop on the form element. When the submit button is clicked, set the state variables to empty strings.

How do I unregister in react hook form?

unregister: (name: string | string[], options) => void This method allows you to unregister a single input or an array of inputs. It also provides a second optional argument to keep state after unregistering an input.

Is react hook form uncontrolled?

React Hook Form relies on uncontrolled form, which is the reason why the register function capture ref and controlled component has its re-rendering scope with Controller or useController .


1 Answers

You can send a new set of values to the reset. Since you do receive a set of values in the submit handler, you could connect both functionalities in the following way:

const {reset, handleSubmit, formState} = useForm();
const {isDirty} = formState;

const handleFormSubmit = (values) =>
{
    //This would be the call where you post your info
    fetch('google.com')
    .then(response => console.log('response', response))
    .finally(() => reset(values));
}

Notice the reset(values) in the example above, which will reset your form to the values it tried to submit. Thus, rendering isDirty back to false.

This is a rather common need in forms that do not reload or redirect after sending the information, so I assume they will eventually create a cleaner way to do it.

like image 62
Ale Avatar answered Oct 14 '22 13:10

Ale