T
TanStack3mo ago
harsh-harlequin

onChangeAsync errors not in the form state errors

I noticed something: When we have a field with onChangeAsync validation, the error throwed by the validation doesnt update form state errors (form state errors is still empty, even though canSubmit and isValid are falses). Is this a bug or intentional? Repro: https://stackblitz.com/edit/vitejs-vite-w4gzoqsg?file=src%2FApp.tsx
Matheus
StackBlitz
Asynchronous defaultValues with validation (duplicated) - StackBlitz
Next generation frontend tooling. It's fast!
3 Replies
flat-fuchsia
flat-fuchsia3mo ago
field validators are only for the field validation. This means they are accessible in two locations: * The field itself * The form's fieldMetaBase In the example, you're accessing form.state.errors which is for Form-level errors. You can set field level errors from the form, but you can't set form-level errors from the field. If you need it accessible on the form level, then a form validator will be the best way to go TL;DR it's intentional since form.state.errors is for form-level errors
harsh-harlequin
harsh-harlequinOP3mo ago
Thanks @Luca | LeCarbonator So it means I would have to apply async on change for all form? In my use case, I have a text input (user name) which is conditionally rendered by another Boolean field (customize username). Yes, we do it because that is a pro feature so UX is better in this way. So this case you would recommend to use refine (since I am using zod), so that would run whenever any value from the form changes, right)? Then I would have to check if value of alias has changed to otherwise not call server every time any field changes. Also, this would potentially make my spinner loading on the alias field to run all the time any field is validating. Was not very intuitive to have form blocked because is valid is false, but at same time no errors displayed in the form, because at the end error is in field internal state only. Form validator can easily become a nightmare. But I guess this is just as it is… Another question. Across Tanstack.com I have seen different usage of errors for both sending/displaying error messages. Sometimes you access errors[].message and sometimes not. Error is not type safe, is this intentional too? Any recommended way to make it safer? (I can provide more examples on this too).
flat-fuchsia
flat-fuchsia3mo ago
Errors are type safe, but they can be any value. So if you are using form composition (where errors could come from anything), they will be typed as unknown. If you‘re in the form location, it should be properly typed. Do you have an example of that unsafe error? The username validation depends on where you want the error to be displayed. If it‘s right next to the username field, then a field validator is perfect for it. Generally, examples will focus on form validation because it‘s more easily readable (logic section of your code vs. JSX section)

Did you find this page helpful?