Skip to content

Commit 926d9d0

Browse files
authored
Merge pull request #65 from DouglasNeuroInformatics/dev
feat: allow users to return an error from onSubmit in form
2 parents 6a2164b + 496c956 commit 926d9d0

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

src/components/Form/Form.tsx

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@ import { getInitialValues } from './utils';
2424

2525
import type { FormErrors } from './types';
2626

27+
type FormSubmitResult = { errorMessage: string; success: false } | { success: true };
28+
29+
type FormSubmitHandler<TData> = (data: NoInfer<TData>) => Promisable<FormSubmitResult | void>;
30+
2731
type FormProps<TSchema extends ZodTypeLike<FormDataType>, TData extends TSchema['_output'] = TSchema['_output']> = {
2832
[key: `data-${string}`]: unknown;
2933
additionalButtons?: {
@@ -39,11 +43,9 @@ type FormProps<TSchema extends ZodTypeLike<FormDataType>, TData extends TSchema[
3943
fieldsFooter?: React.ReactNode;
4044
id?: string;
4145
initialValues?: PartialNullableFormDataType<NoInfer<TData>>;
42-
onBeforeSubmit?:
43-
| ((data: NoInfer<TData>) => Promisable<{ errorMessage: string; success: false } | { success: true }>)
44-
| null;
46+
onBeforeSubmit?: FormSubmitHandler<NoInfer<TData>> | null;
4547
onError?: (error: ZodErrorLike) => void;
46-
onSubmit: (data: NoInfer<TData>) => Promisable<void>;
48+
onSubmit: FormSubmitHandler<NoInfer<TData>>;
4749
preventResetValuesOnReset?: boolean;
4850
readOnly?: boolean;
4951
resetBtn?: boolean;
@@ -121,7 +123,7 @@ const Form = <TSchema extends ZodTypeLike<FormDataType>, TData extends TSchema['
121123
}
122124
if (onBeforeSubmit) {
123125
const beforeSubmitResult = await onBeforeSubmit(result.data);
124-
if (!beforeSubmitResult.success) {
126+
if (beforeSubmitResult && !beforeSubmitResult.success) {
125127
setErrors({});
126128
setRootErrors([beforeSubmitResult.errorMessage]);
127129
return;
@@ -130,12 +132,17 @@ const Form = <TSchema extends ZodTypeLike<FormDataType>, TData extends TSchema['
130132

131133
try {
132134
setIsSubmitting(true);
133-
await Promise.all([
135+
const [formSubmitResult] = await Promise.all([
134136
onSubmit(result.data),
135137
new Promise<void>((resolve) => {
136138
return suspendWhileSubmitting ? setTimeout(resolve, 500) : resolve();
137139
})
138140
]);
141+
if (formSubmitResult && !formSubmitResult.success) {
142+
setErrors({});
143+
setRootErrors([formSubmitResult.errorMessage]);
144+
return;
145+
}
139146
reset();
140147
} finally {
141148
setIsSubmitting(false);

0 commit comments

Comments
 (0)