Whenever the server returns validation errors and we would set them with setFieldError
they would be lost if any field would get a change or blur event. But we want to keep these kind of errors until the specific field changes. Additional we want to handle generic server errors (which are not specific to a field, but the whole form).
With these hooks field specific server side errors should be added like this:
const { setStatus } = useFormikContext();
const errors = {};
// adjust serverErrors to your own responses
// in this case they look like this: Array<{ name: string, error: string }>
serverErrors.forEach(({ name, error }) => (errors = setIn(errors, field, error)));
setStatus(errors);
Global server errors should be added like this:
const { setStatus } = useFormikContext();
setStatus(true);
You should use useGlobalErrorHandler
once inside your form and useErrorHandler
once for every field. It could look like this:
type Props = {
name: string;
} & InputHTMLAttributes<HTMLInputElement>;
export const Input: FC<Props> = (props) => {
const { name, ...inputProps } = props;
const [field, meta] = useField(name);
const [showError, serverError] = useErrorHandler(field, meta);
return (
<>
<input
style={{ borderColor: showError ? 'red' : 'black' }}
{...field}
{...inputProps}
/>
{showError && (serverError || meta.error) && (
<p>{serverError || meta.error}</p>
)}
</>
);
};
Can you post the implementation of
usePrevious
? Also youruseGlobalErrorHandler
function syntax is broken.