Open History to see the last commit
1import { initializeForm, useInternalForm } from './PreactFormApi.lib'
2import type {
3 FormOptions,
4 FormValidators,
5 ToFormErrorTypes,
6} from '@tanstack/form-core'
7import type {
8 AnyPreactFormComponentMap,
9 DefaultPreactFormComponentMap,
10} from '../AppForm/componentMap.public'
11import type { PreactFormApi } from './formApiTypes.public'
12β
13export type UseFormHook<in out TComponents extends AnyPreactFormComponentMap> =
14 <
15 TFormData,
16 const TFormValidators extends FormValidators<TFormData>,
17 TSubmitReturn,
18 >(
19 options: FormOptions<TFormData, TFormValidators, TSubmitReturn, unknown>,
20 ) => PreactFormApi<
21 TFormData,
22 ToFormErrorTypes<TFormValidators, TSubmitReturn>,
23 TComponents
24 >
25β
26function useFormHook(options: FormOptions<any, any, any, unknown>) {
27 const form = useInternalForm(options, initializeForm)
28 return form
29}
30β
31/**
32 * Creates a Preact form whose instance and lifecycle are owned by the current
33 * component.
34 *
35 * `defaultValues` establish the initial state and inferred form value type.
36 * Later renders apply changed options to the same form instance, and unmounting
37 * the component cleans it up.
38 *
39 * Call this hook at the top level of a Preact component or custom hook.
40 *
41 * @example
42 * ```tsx
43 * function ProfileForm() {
44 * const form = useForm({
45 * defaultValues: { name: '' },
46 * onSubmit: ({ value }) => saveProfile(value),
47 * })
48 *
49 * return (
50 * <form
51 * onSubmit={(event) => {
52 * event.preventDefault()
53 * void form.handleSubmit()
54 * }}
55 * />
56 * )
57 * }
58 * ```
59 *
60 * @returns The Preact form API with typed field, subscription, and form-group
61 * components attached.
62 */
63const useForm =
64 useFormHook as never as UseFormHook<DefaultPreactFormComponentMap>
65β
66export { useForm }