I have form some prefilled values from api and i set them with
setValues('input-field-name','value-got-from-api')
and when a i use reset method of react-hook-form it resets the newly added data but it does not reset the whole data in fields. For example. if a input fields value with setValue previously is 123
and if i typed 123abc
it resets the abc
part and sets the fields to 12345
. But i wanted to reset to null or blank form.
The direct question will be , how can i reset the form fields either by using plain js or using react-hook-form ?
PS: i tried reset()
method from rect-hook-form and plain js reset document.getElementById('myform').reset();
but noting works.
CodePudding user response:
You can use the reset
method returned from useForm
hook.
export default function App() {
const { register, handleSubmit, reset } = useForm();
const onSubmit = (data, e) => {};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("firstName", { required: true })} />
<input {...register("lastName")} />
<input type="button" onClick={() => {
reset({
firstName: "default value",
}, {
keepErrors: true,
keepDirty: true,
keepIsSubmitted: false,
keepTouched: false,
keepIsValid: false,
keepSubmitCount: false,
});
}} />
</form>
);
}