Replies: 1 comment
|
If your import { useForm } from 'react-hook-form';
type Option = { label: string; value: string };
// Pass the query's data here; undefined means it hasn't loaded yet.
function ItemForm({ options }: { options: Option[] | undefined }) {
const { register, handleSubmit } = useForm({
defaultValues: { item: '5' },
});
return (
<form onSubmit={handleSubmit(console.log)}>
{options === undefined ? (
<p>Loading options…</p>
) : (
<label>
Item
<select {...register('item')}>
<option value="">Select an item</option>
{options.map(option => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</label>
)}
<button type="submit" disabled={options === undefined}>Submit</button>
</form>
);
}This ensures the matching option exists when RHF registers the element. A native select cannot display Handle query errors separately, and keep the loaded select mounted during background refetches; don't reset the field every time a new options array arrives. If the fetched list doesn't contain I verified this pattern with RHF 7.88.0 / React 19.2.4 in a React Testing Library + jsdom test under StrictMode: the delayed list selects and submits If you mean the literal boolean |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Pretty much title, I suspect this is because RHF is using the ref to set the value instead of using the
valueprop. But what is standard practice if you have a default form value that is immediately accessible but the options are fetched async?Something like:
What is the standard practice?
All reactions