TypeScript: How to set a Form Error that is not associated with a Field? #7803
Unanswered
thomasdax98
asked this question in
Q&A
Replies: 2 comments 4 replies
-
RHF doesn't support gloabal error field ATM. |
Beta Was this translation helpful? Give feedback.
1 reply
-
It is explained how to accomplish this at the 5:50 mark in this video by Bill (RHF author): This is the pattern that I use based on the video: const schema = z.object({
name: z.string(),
email: z.string().email(),
// This is just to make the "field" available in TypeScript. It will never
// have a value assigned to it and JSON.stringify will filter it out.
// The TypeScript type resolves to: void | undefined
serverError: z.void(),
})
function MyComponent(props) {
const {
formState: { errors, isSubmitting, isSubmitSuccessful },
handleSubmit,
register,
setError,
} = useForm<z.output<typeof schema>>({
resolver: zodResolver(schema),
})
return (
<form
onSubmit={(event) =>
handleSubmit(async (values) => {
const result = await doMySignupApiCall(values)
if (result.userErrors.length > 0) {
// Display errors for individual fields where remote validations fail
for (const userError of result.userErrors) {
setError(userError.field, { message: userError.message })
}
return
}
// Do stuff here with the successful result like trigger callbacks, etc
props.onSubmitSuccessful?.()
})(event).catch((error) => {
// If the request fails due to network error or something that does not apply to a single field
setError("serverError", { type: "server", message: error?.message })
})
}
>
{!isSubmitSuccessful ? (
<>
<div>
<input {...register("name")} />
<ErrorMessage name="name" errors={errors} />
</div>
<div>
<input type="email" {...register("email")} />
<ErrorMessage name="email" errors={errors} />
</div>
<div>
<button disabled={isSubmitting}>Sign up</button>
</div>
{errors.serverError && (
<p>An unexpected error has occurred. Please try again later.</p>
)}
</>
) : (
<p>Thank you for signing up!</p>
)}
</form>
)
} |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I've implemented a form that submits its data to an API. If an error occurs in the API, the error is returned. This error is not associated with any field.
I want to show the error using setError(). According to the example here (https://github.com/react-hook-form/react-hook-form/blob/master/src/types/form.ts#L517) it should be possible to add an error like this:
setError("serverError", { type: "server", message: "Error occurred"})
.However the type definition of setError prevents this because it only allows a FieldValue as name (
name: FieldPath<TFieldValues>
).Here is an excerpt of my code:
How can I use "serverError" as
name
without triggering a type error? Is this a bug in the type definitions?Beta Was this translation helpful? Give feedback.
All reactions