'react hook forms is showing me incorrect (0) characters entered in text field and then correct field length on second click of submit
I am using getValues with react-hook-form and then trying to render the length of the characters of the text field in an error message when user goes over the limit. I am seeing 0/1046 characters when i click submit the first time then the second time I see the correct number.
const titleValue = getValues('title')
const descriptionValue = getValues('description')
<TextField
name='title'
defaultValue=''
label='Title*'
control={control}
css={{}}
help={
errors.title?.type === 'required' || errors.title?.type === 'maxLength'
? errors.title.message
: undefined
}
aria-label='title'
rules={{
required: { value: true, message: 'Required' },
maxLength: {
value: 1024,
message: `${titleValue?.length || 0}/1024 maximum character length exceeded`,
},
}}
/>
Solution 1:[1]
react-hook-form provided an answer https://github.com/react-hook-form/react-hook-form/discussions/7668
validate: (value) => {
if (value.length >= 10) {
// this will give you the correct value for your error message
return `Please, enter a title with less than 10 characters (${value.length}/10)`;
}
}
}}```
Solution 2:[2]
Please refer to useForm - getValues
An optimized helper for reading form values. The difference between watch and getValues is that getValues will not trigger re-renders or subscribe to input changes.
Where as useForm - watch seems to fit your needs more.
This will watch specified inputs and return their values. It is useful for determining what to render.
const titleValue = watch('title')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gena |
| Solution 2 | Ben |

