Skip to content

Commit

Permalink
add pre submit hook for forms
Browse files Browse the repository at this point in the history
  • Loading branch information
alexlanz committed Dec 3, 2024
1 parent 8587927 commit 8e4248c
Showing 1 changed file with 22 additions and 10 deletions.
32 changes: 22 additions & 10 deletions src/components/react-hook-form/Form.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { ForwardedRef, forwardRef } from 'react'
import {
ComponentPropsWithRef,
FormEvent,
ForwardedRef,
forwardRef,
} from 'react'
import {
FieldValues,
FormProvider,
Expand All @@ -8,22 +13,18 @@ import {

type NoInfer<T> = [T][T extends unknown ? 0 : never]

type HTMLFormProps = React.DetailedHTMLProps<
React.FormHTMLAttributes<HTMLFormElement>,
HTMLFormElement
>

export type FormProps<
TFieldValues extends FieldValues = FieldValues,
TContext = unknown,
TTransformedValues extends FieldValues | undefined = undefined,
> = Omit<HTMLFormProps, 'onSubmit'> & {
> = Omit<ComponentPropsWithRef<'form'>, 'onSubmit'> & {
form: UseFormReturn<TFieldValues, TContext, TTransformedValues>
onSubmit?: TTransformedValues extends undefined
? SubmitHandler<NoInfer<TFieldValues>>
: TTransformedValues extends FieldValues
? SubmitHandler<NoInfer<TTransformedValues>>
: never
onPreSubmit?: (e: FormEvent<HTMLFormElement>) => void | Promise<void>
}

export const Form = forwardRef(function Form<
Expand All @@ -34,19 +35,30 @@ export const Form = forwardRef(function Form<
{
form,
onSubmit,
onPreSubmit,
children,
...props
}: FormProps<TFieldValues, TContext, TTransformedValues>,
ref: ForwardedRef<HTMLFormElement>,
) {
const handleFormSubmit = onSubmit
? async (e: FormEvent<HTMLFormElement>) => {
if (onPreSubmit) {
await onPreSubmit(e)
}

return form.handleSubmit(onSubmit)
}
: undefined

return (
<FormProvider<TFieldValues, TContext, TTransformedValues> {...form}>
<form
{...props}
ref={ref}
onSubmit={(event) => {
onSubmit ? void form.handleSubmit(onSubmit)(event) : undefined
}}
onSubmit={
handleFormSubmit ? (e) => void handleFormSubmit(e) : undefined
}
>
{children}
</form>
Expand Down

0 comments on commit 8e4248c

Please sign in to comment.