简体   繁体   中英

React-hook-form doesn't change the form validity when React-Select is changed

I have a react-hook-form with a react-select:

  • When I change the value of react-select, the form becomes both dirty and valid.
  • The submit button is now enabled and the form can be sent.
  • Once the form is sent, useForm defaultValue's are reset to the new values
  • The submit button is disabled again, waiting for a change in the form.
  • When I change again react-select value, the form is not dirty. The button remains disabled. Yet, the react-select value has changed.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM