Created
July 18, 2022 17:43
-
-
Save gastonambrogi/21ac51ba23628d045374ba7006dd7482 to your computer and use it in GitHub Desktop.
REACT:: add custom errors to state
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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