mirror of
https://gitlab.com/mbugroup/lti-web-client.git
synced 2026-05-21 13:55:45 +00:00
63 lines
1.5 KiB
TypeScript
63 lines
1.5 KiB
TypeScript
import { getUniqueFormikErrors } from '@/lib/formik-helper';
|
|
import { FormikProps } from 'formik';
|
|
import { useState } from 'react';
|
|
|
|
interface UseFormikErrorListOptions {
|
|
onBeforeSubmit?: (e: React.FormEvent<HTMLFormElement>) => boolean | void;
|
|
onAfterValidation?: () => void | Promise<void>;
|
|
}
|
|
|
|
export const useFormikErrorList = <T>(
|
|
formik: FormikProps<T>,
|
|
options?: UseFormikErrorListOptions
|
|
) => {
|
|
const [formErrorList, setFormErrorList] = useState<string[]>([]);
|
|
|
|
const handleValidateForm = async () => {
|
|
const errors = await formik.validateForm();
|
|
|
|
if (Object.keys(errors).length > 0) {
|
|
const errorMessages = getUniqueFormikErrors(errors);
|
|
setFormErrorList(errorMessages);
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
};
|
|
|
|
const handleFormSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
|
e.preventDefault();
|
|
|
|
// Call onBeforeSubmit callback
|
|
if (options?.onBeforeSubmit) {
|
|
const shouldContinue = options.onBeforeSubmit(e);
|
|
if (shouldContinue === false) {
|
|
return; // Cancel submit
|
|
}
|
|
}
|
|
|
|
// Validate form
|
|
const isValid = await handleValidateForm();
|
|
|
|
// Call onAfterValidation callback if validation passed
|
|
if (options?.onAfterValidation) {
|
|
await options.onAfterValidation();
|
|
}
|
|
|
|
// Submit form
|
|
formik.handleSubmit();
|
|
};
|
|
|
|
const close = () => {
|
|
setFormErrorList([]);
|
|
};
|
|
|
|
return {
|
|
formErrorList,
|
|
setFormErrorList,
|
|
close,
|
|
handleValidateForm,
|
|
handleFormSubmit,
|
|
};
|
|
};
|