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

useForm.tsx

80 lines2.5 KB

1import type { FormState, FormOptions, Validator } from '@tanstack/form-core'
2import { FormApi, functionalUpdate } from '@tanstack/form-core'
3import type { NoInfer } from '@tanstack/react-store'
4import { useStore } from '@tanstack/react-store'
5import React, {
6 type PropsWithChildren,
7 type ReactNode,
8 useState,
9} from 'rehackt'
10import { type UseField, type FieldComponent, Field, useField } from './useField'
11import { formContext } from './formContext'
12import { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect'
13​
14declare module '@tanstack/form-core' {
15 // eslint-disable-next-line no-shadow
16 interface FormApi<TFormData, TFormValidator> {
17 Provider: (props: PropsWithChildren) => JSX.Element
18 Field: FieldComponent<TFormData, TFormValidator>
19 useField: UseField<TFormData>
20 useStore: <TSelected = NoInfer<FormState<TFormData>>>(
21 selector?: (state: NoInfer<FormState<TFormData>>) => TSelected,
22 ) => TSelected
23 Subscribe: <TSelected = NoInfer<FormState<TFormData>>>(props: {
24 selector?: (state: NoInfer<FormState<TFormData>>) => TSelected
25 children: ((state: NoInfer<TSelected>) => ReactNode) | ReactNode
26 }) => JSX.Element
27 }
29​
30export function useForm<
31 TFormData,
32 TFormValidator extends Validator<TFormData, unknown> | undefined = undefined,
33>(
34 opts?: FormOptions<TFormData, TFormValidator>,
35): FormApi<TFormData, TFormValidator> {
36 const [formApi] = useState(() => {
37 // @ts-ignore
38 const api = new FormApi<TFormData, TFormValidator>(opts)
39​
40 api.Provider = function Provider(props) {
41 useIsomorphicLayoutEffect(api.mount, [])
42 return (
43 <formContext.Provider {...props} value={{ formApi: api as never }} />
44 )
45 }
46 api.Field = Field as any
47 api.useField = useField as any
48 api.useStore = (
49 // @ts-ignore
50 selector,
51 ) => {
52 // eslint-disable-next-line react-hooks/rules-of-hooks
53 return useStore(api.store as any, selector as any) as any
54 }
55 api.Subscribe = (
56 // @ts-ignore
57 props,
58 ) => {
59 return functionalUpdate(
60 props.children,
61 // eslint-disable-next-line react-hooks/rules-of-hooks
62 useStore(api.store as any, props.selector as any),
63 ) as any
64 }
65​
66 return api
67 })
68​
69 formApi.useStore((state) => state.isSubmitting)
70​
71 /**
72 * formApi.update should not have any side effects. Think of it like a `useRef`
73 * that we need to keep updated every render with the most up-to-date information.
74 */
75 useIsomorphicLayoutEffect(() => {
76 formApi.update(opts)
77 })
78​
79 return formApi as any