So, why isn't useWatch pulling control from the context?
#13149
|
I tried to find an issue that mentioned this but I couldn't find any. Which is confusing me even more. Is there a particular reason why |
Replies: 5 comments
|
In the current implementation, it effectively does: const formControl = useFormControlContext()
const { control = formControl } = props || {}So this works: <FormProvider {...methods}>
<Child />
</FormProvider>
function Child() {
const value = useWatch({ name: 'fieldName' })
return <>{value}</>
}If you still get an error, the usual causes are:
So I don’t think you should need to pass |
|
From the docs: What usually causes the error
// parent
const methods = useForm()
return (
<FormProvider {...methods}>
<Child />
</FormProvider>
)
// child
function Child() {
// control comes from context — no prop required
const value = useWatch({ name: "email" })
return <span>{value}</span>
}If
// this does NOT create context
const { register, control } = useForm()
return (
<form>
<Child /> {/* useWatch() here fails */}
</form>
)Here you must pass
Watching the whole form still needs a control source: useWatch() // needs FormProvider
useWatch({ name: "x" }) // same
useWatch({ control, name: "x" }) // always fineWhy it feels different from other hooksHooks like Pattern that scales
function PriceField({ control }: { control?: Control<FormValues> }) {
const price = useWatch({ control, name: "price" })
// …
}If you still get the error with a provider in place, the next place to check is whether the watching component is under a second React tree (portal target, another root, test harness) that does not include the provider. |
|
One small correction to the portal advice above: rendering into So if your input is in a modal, check how that modal is mounted. A normal portal created beneath React explains the distinction in the portal docs. That can save you from adding another provider when the portal itself isn't the problem. AI-assisted reply; checked against the React documentation. |
|
Thank you for your responses guys and sorry for the late reply. If I remember correctly, I meant to say TypeScript error not runtime. If I'm not mistaken, control is not optional for useWatch in the type system. I should have been more clear. If it already pulls control from context, the type should also be optional. Am I mistaken? |
|
|
controlis optional in the currentuseWatchtypes too, including when you passname