Home > Enterprise >  mui autocomplete with react-hook-form: defaultValue in formData
mui autocomplete with react-hook-form: defaultValue in formData

Time:12-26

I'm setting the defaultValue of the Autocopmlete component as below:

<Controller
  control={control}
  name={name}
  render={({field: {onChange, value}}) => (
    <Autocomplete
      freeSolo={freeSolo}
      options={options}
      renderInput={params => {
        return <TextField {...params} label={label} margin="normal" variant="outlined" onChange={onChange} />
      }}
      onChange={(event, values, reason) => onChange(values)}
      defaultValue={defaultValue}
    />
  )}
/>

the value is well displayed based on the defaultValue. However when I click on the submit button, the value of the Autocomplete field is always undefined if I don't use the autocomplete component. Here are how I register the hook and component (simplified code)

const customerSchema = yup.object().shape({
  route: yup.string().nullable()
})
  
const {control, handleSubmit} = useForm({
    resolver: yupResolver(customerSchema)
  })

  const onSubmit = formData => {
    console.log(formData) // autocomplete is undefined if no action on the autocomplete 
  }

<form noValidate autoComplete="off" onSubmit={handleSubmit(onSubmit)}>
 <AutoCompleteInput
        control={control}
        name="route"
        label="route"
        options={customers_routes.map(option => option.route_name)}
        defaultValue={customer.route}
        freeSolo={false}
      />
  <Button type="submit">
        Update
      </Button>
  </form>

What should I do to have the route field always available in the form data when I click on submit?

CodePudding user response:

Why don't you use defaultValues option with useForm:

const {control, handleSubmit} = useForm({
  resolver: yupResolver(customerSchema),
  defaultValues: { route: customer.route },
});

and instead of sending defaultValue prop to AutoComplete you can use value prop, like this:

<Controller
  control={control}
  name={name}
  render={({ field: { onChange, value } }) => (
      <Autocomplete
        freeSolo={freeSolo}
        options={options}
        renderInput={(params) => {
          return (
            <TextField
              {...params}
              label={label}
              margin="normal"
              variant="outlined"
              onChange={onChange}
            />
          );
        }}
        onChange={(event, values, reason) => onChange(values)}
        value={value}
      />
  )}
/>
  • Related