From 8e4248ca10ca69546c2c2f7775864225e718c660 Mon Sep 17 00:00:00 2001 From: Alex Lanz Date: Tue, 3 Dec 2024 15:31:45 +0100 Subject: [PATCH] add pre submit hook for forms --- src/components/react-hook-form/Form.tsx | 32 +++++++++++++++++-------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/src/components/react-hook-form/Form.tsx b/src/components/react-hook-form/Form.tsx index 76038dd9..21ca4d70 100644 --- a/src/components/react-hook-form/Form.tsx +++ b/src/components/react-hook-form/Form.tsx @@ -1,4 +1,9 @@ -import { ForwardedRef, forwardRef } from 'react' +import { + ComponentPropsWithRef, + FormEvent, + ForwardedRef, + forwardRef, +} from 'react' import { FieldValues, FormProvider, @@ -8,22 +13,18 @@ import { type NoInfer = [T][T extends unknown ? 0 : never] -type HTMLFormProps = React.DetailedHTMLProps< - React.FormHTMLAttributes, - HTMLFormElement -> - export type FormProps< TFieldValues extends FieldValues = FieldValues, TContext = unknown, TTransformedValues extends FieldValues | undefined = undefined, -> = Omit & { +> = Omit, 'onSubmit'> & { form: UseFormReturn onSubmit?: TTransformedValues extends undefined ? SubmitHandler> : TTransformedValues extends FieldValues ? SubmitHandler> : never + onPreSubmit?: (e: FormEvent) => void | Promise } export const Form = forwardRef(function Form< @@ -34,19 +35,30 @@ export const Form = forwardRef(function Form< { form, onSubmit, + onPreSubmit, children, ...props }: FormProps, ref: ForwardedRef, ) { + const handleFormSubmit = onSubmit + ? async (e: FormEvent) => { + if (onPreSubmit) { + await onPreSubmit(e) + } + + return form.handleSubmit(onSubmit) + } + : undefined + return ( {...form}>
{ - onSubmit ? void form.handleSubmit(onSubmit)(event) : undefined - }} + onSubmit={ + handleFormSubmit ? (e) => void handleFormSubmit(e) : undefined + } > {children}