Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add pre submit hook for forms #327

Merged
merged 1 commit into from
Dec 3, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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