Repository navigation
Replies: 1 comment
|
Yes. In the current v1 API, put the message in the form's error map with For an error returned by your existing save request, adapt the hook like this ( import { useForm } from '@tanstack/react-form';
const form = useForm({
defaultValues: { email: '' },
validators: {
// Gives the onSubmit error slot a string | undefined type.
// Keep your existing field/onChange validators too.
onSubmit: (): string | undefined => undefined,
},
onSubmit: async ({ value, formApi }) => {
try {
await saveProfile(value);
} catch (error) {
formApi.setErrorMap({
onSubmit: 'Could not save your changes. Please try again.',
});
throw error;
}
},
});Render the banner above your form: <>
<form.Subscribe selector={(state) => state.errorMap.onSubmit}>
{(message) => message ? <div role="alert">{message}</div> : null}
</form.Subscribe>
<form onSubmit={(e) => {
e.preventDefault();
e.stopPropagation();
// Clear the previous request error before attempting a retry.
form.setErrorMap({ onSubmit: undefined });
void form.handleSubmit().catch(() => {
// The save failure is already represented by the form banner.
});
}}>
{/* Your existing fields and submit button */}
</form>
</>The return annotation on the no-op validator matters: without an inferred string error type, TypeScript may only allow Rethrowing lets For a validation request that runs before saving, another option is returning a form-level error from References: form-level validation and reactive error rendering, typed error maps, and FormApi source: setErrorMap and submission handling. |
Uh oh!
There was an error while loading. Please reload this page.
Hey everyone, I've implemented tanstack form and it's working fine with field level errors. Now the thing is, I've the API errors which I show a component above form with some styling...
I don't see a native way of adding global error to tanstack form api and I've to use a
useState(const [error, setError]) to show the error. Is there any way I can get rid of thisuseStateand use the tanstack form hook?I know I can add this to the field level error but it costs UX... so If someone know any solution to this, it'd be helpful!
All reactions