I've inherited some code that uses MUI v5 controls in a form created with react-hook-form v6. There are some autocomplete controls where I want the selection in one control to update the value of another (as a default; the user can always change it).
Listening to the autocomplete changes with watch() and then calling setValue() on another control works to update the form data, but the inputValue of the autocomplete widget doesn't visibly update. So as far as the user can see, nothing has changed in the second autocomplete, even though the data that's returned in onSubmit() has been updated.
I've tried passing inputValue as a prop to the <Autocomplete>, but since it's being controlled by react-hook-form, that generates an error about the control being changed from uncontrolled to controlled.
This codesandbox demonstrates the issue. Selecting "first" in the thing1 autocomplete should update thing2 to "last". If you click Submit, the form's data will be logged to the console, showing that thing2 has indeed been updated. But the visible UI doesn't change.
As so often happens when trying to explain a bug, a solution occurred to me. I tried calling register() with a different name on the <Autocomplete>. This caused the second autocomplete to update correctly when setValue() was called, but added some unnecessary fields to the submit data. Then I removed the register() call entirely (which had already been there when I started looking at the code). I guess registering a component if it's already a child of a <Controller> is unnecessary, and maybe confuses things. (Maybe the library should throw an error in that case?)
The working custom component that wraps the <Autocomplete> in a <Controller> looks like this:
const ControlledAC = ({ name, control, register, options }) => (
<Controller
name={name}
control={control}
render={(props) => (
<Autocomplete
{...props}
freeSolo
autoSelect
options={options}
onChange={(_, value) => props.onChange(value)}
renderInput={(params) => <TextField {...params} label={name} />}
/>
)}
/>
);
This interaction between MUI and react-hook-form seems a bit magical, though. Is this the right away to programmatically set a value on an <Autocomplete> component?