Search code examples
reactjsreact-hook-form

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?


Solution

  • 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.