-
Hi! I'm working on a form that wants to do an initial Now when resetting the form, I'm doing something like this: methods.reset({ ...methods.getValues(), ...defaultValues });
methods.trigger(); // <-- won't work / won't trigger the validation while validation will run and error are showing like this: methods.reset({ ...methods.getValues(), ...defaultValues });
setTimeout(() => methods.trigger(), 0); // <-- works is that known / intentional? Is |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
It's a known limitation that was partly addressed in issue #9863. Regarding your specific use case, there are two aspects to consider:
reset(defaultValues, {
keepValues: true
});
Check out this codesandbox for example. import { useEffect } from "react"
import { useForm } from "react-hook-form"
const defaultValues = {
name: ""
}
function App() {
const { formState, handleSubmit, register, reset, trigger } = useForm({
defaultValues
})
const { errors, isDirty } = formState
useEffect(() => {
if (!isDirty) {
trigger()
}
}, [isDirty, trigger])
return (
<form onSubmit={handleSubmit(console.log)}>
<label>
Name
<input
{...register("name", {
required: "REQUIRED",
minLength: { value: 10, message: "MIN 10 CHAR" }
})}
/>
</label>
{errors.name && <p role="alert">{errors.name.message}</p>}
<button
type="button"
onClick={() => {
reset(defaultValues, {
keepValues: true
})
}}
>
Reset
</button>
<button type="submit">Submit</button>
</form>
)
}
export default App |
Beta Was this translation helpful? Give feedback.
-
Would checking isReady still work with a separate useEffect, to only check initial render? useEffect(() => {
if (isReady) {
form.trigger();
}
}, [form, isReady]); and what if we already reset values with useEffect(() => {
form.reset(defaultValues);
}, [form, defaultValues]); in such a case, even if they work fine, two useEffects seems a bit redundant |
Beta Was this translation helpful? Give feedback.
It's a known limitation that was partly addressed in issue #9863.
Regarding your specific use case, there are two aspects to consider:
reset
values, you can utilize thekeepValues
property of thereset
method to retain the previously entered values:isDirty
state of the form. This state should reset along with the form, as you're providing new default values for the form.Check out this codesandbox for example.