I have a react-hook-form with a react-select:
useForm
defaultValue's are reset to the new values I have tried almost everything: replace onChange
by setValue("name", value, {shouldDirty: true}
, etc.
Here is the code:
import { useForm, Controller } from "react-hook-form"; import Select from "react-select"; const options = [ { value: "joe", label: "Joe" }, { value: "jack", label: "Jack" }, { value: "averell", label: "Averell" } ]; type Data = { name: string; surname: string }; export default function Form({ defaultValues, onSend }: { defaultValues: Data; onSend: (data: Data) => void; }) { const { register, handleSubmit, reset, getValues, control, formState: { isValid, isDirty } } = useForm({ mode: "onChange", defaultValues }); const onSubmit = (data: Data) => { onSend(data); reset(getValues()); console.log("data sent!", data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <Controller control={control} name="name" render={({ field }) => ( <Select {...field} value={field.value} options={options} onChange={(v) => field.onChange(v)} /> )} /> <input placeholder="surname" {...register("surname")}/> <button type="submit" disabled={!isValid || !isDirty}> submit </button> </form> ); }
How to fix this?
ps: here is also a sandbox: https://codesandbox.io/s/react-hook-form-test-8tdq3?file=/src/FormController.tsx
So the answer is that I needed to add a useEffect to reset the form values after the submission:
useEffect(() => { if (formState.isSubmitSuccessful) { reset(getValues()); } }, [formState, getValues, reset]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.