New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Bug]: Value of useControlField
is undefined
on first render
#351
Comments
Have you tried using export const MyForm = () => {
const [value, setValue] = useControlField(
"myField",
"myForm"
);
useEffect(() => {
// Now we can update the value of the field
// for whatever reason we need.
setValue("Some value");
});
return (
<ValidatedForm validator={myValidator} id="myForm">
<MyInput
name="myField"
// This assumes your input component
// has a `value` and `onChange` prop
value={value}
onChange={(e) => setValue(e.target.value)}
/>
</ValidatedForm>
);
}; Example in here: |
I'm not quite sure what the example demostrates. I've added P.S. I had a small mistake in my initial example: |
I consider it a bug as well. The workaround is to read the |
This happens only when using I think a potential API improvement we could make here is to allow passing a default value directly into the hook like you mentioned. But this is more of an intentional (if unfortunate) trade-off of the current API, rather than a bug. If you think about it, in code that looks like this, it's impossible for the const { defaultValues } = useLoaderData();
const [value, setValue] = useControlField("myField");
return (
<ValidatedForm
defaultValues={defaultValues}
// ...etc
/>
) There are 3 main ways to fix the issue your observing. Manually provide a defaultconst [firstName = defaultValues.firstName, setFirstName] = useControlField("firstName"); Use
|
Which packages are impacted?
remix-validated-form
@remix-validated-form/with-zod
@remix-validated-form/with-yup
zod-form-data
What version of these packages are you using?
Please provide a link to a minimal reproduction of the issue.
https://github.com/AlexanderKulia/use-control-field-example
Steps to Reproduce the Bug or Issue
yarn install
yarn dev
undefined
before its values changes to "alex"Expected behavior
I expected that the field's initial value is set to whatever is passed in
defaultValues
similar touseState<string>("alex")
. Am I doing something wrong? Because with this behavior I have to change the type tostring | undefined
and handleundefined
which is annoying in complicated dynamic formsScreenshots or Videos
No response
Platform
Additional context
No response
The text was updated successfully, but these errors were encountered: