So, why isn't useWatch pulling control from the context?
#13149
Replies: 1 comment
|
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. |
Uh oh!
There was an error while loading. Please reload this page.
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
useWatchcan't use thecontrolavailable from the context provider? Currently it errors if we don't manually give it thecontrol. Why can't it be like the other hooks that use the context instead?All reactions