Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gastonambrogi/21ac51ba23628d045374ba7006dd7482 to your computer and use it in GitHub Desktop.
Save gastonambrogi/21ac51ba23628d045374ba7006dd7482 to your computer and use it in GitHub Desktop.
REACT:: add custom errors to state
const addCustomValidationError = (
form: Partial<UseFormReturn>,
formKey: string,
message: string
) => {
setCustomValidationErrors((previousState: CustomValidationError[]) => {
const foundForm = previousState.findIndex(
(customerrors) => customerrors.form === form
);
if (foundForm > -1) {
previousState[foundForm].errors.set(formKey, message);
form.setError?.(formKey, {
type: 'custom',
message: message,
});
return previousState;
}
const nextState = [
...previousState,
{
form,
errors: new Map([[formKey, message]]),
},
];
form.setError?.(formKey, {
type: 'custom',
message: message,
});
return nextState;
});
};
const removeCustomValidationError = (
form: UseFormReturn,
formKey?: string
) => {
setCustomValidationErrors((previousState: CustomValidationError[]) => {
const foundForm = previousState.findIndex(
(customerrors) => customerrors.form === form
);
if (foundForm > -1) {
if (formKey) {
previousState[foundForm].errors.delete(formKey);
} else {
previousState.splice(foundForm, 1);
}
}
form.clearErrors(formKey);
return previousState;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment