Home > Software design >  React-hook-form set value as object always selecting 0
React-hook-form set value as object always selecting 0

Time:11-26

When trying to use MUI Autocomplete to select an object from a list of options, the value is set to 0. How can I get it to set the actual object?

Example here: https://codesandbox.io/s/ecstatic-diffie-mf9ydl Select an option from the autocomplete field and click submit. You'll see the valid in the console is 0 instead of { _id: 1, name: "Option 1" }

CodePudding user response:

Any reason that you use such an old version of react-hook-form?

I would recommend updating to a later version and then use the render prop on Controller.

<Controller
  name={country}
  render={(
    { field: { onChange, value, ref }, fieldState: { error } },
    ...other
  ) => (
    <Autocomplete
      options={options}
      getOptionLabel={(option) => option.name}
      getOptionSelected={(option, value) => option._id === value._id}
      onChange={(event, newValue, reason) =>
        onChange(reason === "clear" ? null : newValue)
      }
      renderInput={(params) => <TextField {...params} label="Country" />}
    />
  )}
/>;

CodePudding user response:

In the older version of react-hook-form you can accomplish that by setting onChange={([, data]) => data} on the Controller.

Here you can find examples for old and new: https://github.com/react-hook-form/react-hook-form/discussions/3365#discussioncomment-122808

  • Related