import type {FormEventHandler, FormHTMLAttributes, PropsWithChildren} from 'react'
import {useRef} from 'react'
import type {FieldPath, FieldValues, UseFormReturn} from 'react-hook-form'
import {FormProvider} from 'react-hook-form'
import {CircleX} from 'lucide-react'
interface FormProps
extends PropsWithChildren,
FormHTMLAttributes {
hookForm: UseFormReturn
action: (data: FormData) => void
id?: string
}
function Form({
id,
children,
action,
hookForm,
...formAttributes
}: FormProps) {
const {handleSubmit, formState} = hookForm
const formRef = useRef(null)
const hasBeenValidated = useRef(false)
const onSubmitHandler: FormEventHandler = evt => {
if (!hasBeenValidated.current) {
// If the form has not yet been validated on the client side, we need to prevent the default action (submitting).
evt.preventDefault()
// Validate the form using react-hook-form.
void handleSubmit(() => {
hasBeenValidated.current = true
// Because state and ref update are async and grouped, we cannot immediately re-submit the form because
// this wouldn't give React time to register the updated value of `hasBeenValidated` before the next submit is
// handled.
setTimeout(() => formRef.current?.requestSubmit(), 0)
})(evt)
} else {
// Reset to ensure that the form is validated again on the next submit.
hasBeenValidated.current = false
}
}
return (
)
}
export default Form