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?
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' }) ).
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With