Skip to content
Source
Sign inSign up
TanStack/form
Open History to see the last commit

useForm.public.ts

65 lines1.7 KB

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