Hero Hook Form API / applyServerErrors
Function: applyServerErrors()
applyServerErrors<
TFieldValues>(setError,serverError):void
Defined in: utils/applyServerErrors.ts:98
Applies server-side validation errors to a React Hook Form instance.
Type Parameters
TFieldValues
TFieldValues extends FieldValues
The form data type
Parameters
setError
UseFormSetError<TFieldValues>
React Hook Form’s setError function
serverError
ServerFormError<TFieldValues>
Server error containing field errors
Returns
void
Description
Maps server-returned field errors to React Hook Form’s error state. Useful for displaying validation errors from API responses. This function iterates through the field errors and sets them on the form using React Hook Form’s setError function.
Examples
import { applyServerErrors } from "@rachelallyson/hero-hook-form";
import { useForm } from "react-hook-form";
function MyForm() {
const form = useForm();
const handleSubmit = async (data) => {
try {
const response = await fetch("/api/submit", {
method: "POST",
body: JSON.stringify(data),
});
if (!response.ok) {
const errorData = await response.json();
applyServerErrors(form.setError, errorData);
}
} catch (error) {
console.error("Error:", error);
}
};
return (
<form onSubmit={form.handleSubmit(handleSubmit)}>
{/* form fields go here */}
</form>
);
}With ZodForm error handling:
import { ZodForm, applyServerErrors } from "@rachelallyson/hero-hook-form";
function MyForm() {
const form = useForm();
const handleSubmit = async (data) => {
try {
await submitToServer(data);
} catch (error) {
if (error.fieldErrors) {
applyServerErrors(form.setError, {
fieldErrors: error.fieldErrors,
});
}
}
};
return <ZodForm config={{ schema, fields }} onSubmit={handleSubmit} />;
}See
- ServerFormError for error structure
- ServerFieldError for field error structure