1

I am using react-hook-form validation for my project. I have a select option, when it change I set the value of selected one to another input which is customer but when I submit the form , customer value show empty, How to fix this issue ?

This is my code

function App() {
const [inputs, setInputs] = useState();
const [inputs1, setInputs1] = useState();

const {
register,
formState: { errors },
trigger,
handleSubmit
} = useForm({
defaultValues: {
  searchby: "searchby",
  customers: "",
  firstName: ""
  }
 });

const onSubmit = (data) => {
alert(JSON.stringify(data));
};

const handleInputChanges = (event) => {
const name = event.target.name;
const value = event.target.value;
 setInputs(value);
 setInputs1(value);
};

  return (
<form onSubmit={handleSubmit(onSubmit)}>
  <select
    name="searchby"
    {...register("searchby", {
      required: "password is required."
    })}
    value={inputs}
    onChange={handleInputChanges}
  >
    <option selected value="searchby">
      Search By
    </option>
    <option value="customerID">Custimer ID </option>
    <option value="teleco">Teleco</option>
  </select>
  {errors.searchby && <p>This field is Required</p>}
  <label>Customer: </label>
  <input
    name="customers"
    {...register("customers")}
    value={inputs1}
    onChange={handleInputChanges}
  />

  {errors.customers && <p>This field is Required</p>}

  <label>First name: </label>
  <input {...register("firstName", { required: true })} />
  {errors.firstName && <p>This field is Required</p>}

  <input type="submit" />
  <button
    type="button"
 
      >
    Validate All
     </button>
    </form>
  );
  }

This is what I am getting when I submit the form

enter image description here

Code link : codesandbox.io

1

4 Answers 4

2

When you using {...register('anyFieldName')} it will give your component react-hook-form's new created form-field values and handlers, for example value & onChange handler, and so on. When you use your own value & onChange handler it overrides react-hook-form's given form-field value & onChange handler.

You can learn more about register here

Try like this

 <input
  name="customers"
  {...register("customers")} 
/>

I would recommend use useController hook, because it is more flexible than register. With register your component is not controlled by your own.

2

You're mixing both classic component handling and react-hook-form here. We're going to rely on react-hook-form and go from there.

By looking at the Codesandbox, we will need to do the following changes:

  • firstly, let's get rid of all the state used and all the onChange handlers used.
  • let's change the useForm() invocation to this:
const {
    register,
    formState: { errors },
    setValue,
    handleSubmit
  } = useForm({
    defaultValues: {
      searchby: "searchby",
      customers: "",
      firstName: ""
    }
  });
  • now, we need to extract some of the functions that the register() gives us, in order to change a bit the onChange function
  const {onChange, ...rest} = register('searchby', {required: 'Password is required'})
  • let's create an onSelectChange handler, that will be called every time the value of the select is changed
  const handleSelectChange = (e) => {
    onChange(e);
    //change this to any value / logic you want
    setValue('customers', 'SomeValue')
  }
  • now, what's left is to update the <select/>
      <select
        {...rest}
        onChange={handleSelectChange}
      >
        <option selected value="searchby">
          Search By
        </option>
        <option value="customerID">Custimer ID </option>
        <option value="teleco">Teleco</option>
      </select>

Fully assembled example:

function App() {
  const {
    register,
    formState: { errors },
    setValue,
    handleSubmit
  } = useForm({
    defaultValues: {
      searchby: "searchby",
      customers: "",
      firstName: ""
    }
  });

  const {onChange, ...rest} = register('searchby', {required: 'Password is required'})

  const handleSelectChange = (e) => {
    onChange(e);
    //change this to any value / logic you want
    setValue('customers', 'SomeValue')
  }

  const onSubmit = (data) => {
    alert(JSON.stringify(data));
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <select
        {...rest}
        onChange={handleSelectChange}
      >
        <option selected value="searchby">
          Search By
        </option>
        <option value="customerID">Custimer ID </option>
        <option value="teleco">Teleco</option>
      </select>
      {errors.searchby && <p>This field is Required</p>}
      <label>Customer: </label>
      <input
        name="customers"
        {...register("customers")}
      />

      {errors.customers && <p>This field is Required</p>}

      <label>First name: </label>
      <input {...register("firstName", { required: true })} />
      {errors.firstName && <p>This field is Required</p>}

      <input type="submit" />
      <button type="button">Validate All</button>
    </form>
  );
}
1

The register method provides ref, value, onChange and onBlur for your input, but you can use the second parameter to pass a custom onChange and use setValue to update the customers input:

const {
    register,
    formState: { errors },
    trigger,
    handleSubmit,
    setValue
  } = useForm({
    defaultValues: {
      searchby: "searchby",
      customers: "",
      firstName: ""
    }
  });

...


const handleInputChanges = (event) => {
  const value = event.target.value;
  setValue("customers", value);
};

...

<select
  name="searchby"
  {...register("searchby", {
    onChange: handleInputChanges,
    required: "password is required."
  })}
>
  <option selected value="searchby">
    Search By
  </option>
  <option value="customerID">Custimer ID </option>
  <option value="teleco">Teleco</option>
</select>

Edit react-hook-form (forked)

2
  • Thanks @Fraction for your answer, how if we call an API based on selection option and setValue to customer ?
    – kick
    Nov 23, 2022 at 2:55
  • 1
    Just call your API and set the value when it is resolved, ex myAPI().then(res => setValue("customers", res));, you can also use async/await
    – Fraction
    Nov 23, 2022 at 8:52
0

The problem here is you are setting the "customers" input value dynamically when selecting the "searchBy" select value. In this case the onChange event for "customers" will not be triggered. But will be triggered on typing value.

One of the solution will be adding the dynamically changed "customers" value at the time of onsubmit trigger without the help of react-use-form

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.