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

useForm.tsx

301 lines8.2 KB

1'use client'
2​
3import { FormApi, functionalUpdate, mergeAndUpdate } from '@tanstack/form-core'
4import { useSelector } from '@tanstack/react-store'
5import { useMemo, useRef, useState } from 'react'
6import { Field } from './useField'
7import { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect'
8import { useFormId } from './useFormId'
9import { FormGroup } from './useFormGroup'
10import type { FormGroupComponent } from './useFormGroup'
11import type {
12 AnyFormApi,
13 AnyFormState,
14 FormAsyncValidateOrFn,
15 FormOptions,
16 FormState,
17 FormValidateOrFn,
18} from '@tanstack/form-core'
19import type { FunctionComponent, PropsWithChildren, ReactNode } from 'react'
20import type { FieldComponent } from './useField'
21​
22/**
23 * Fields that are added onto the `FormAPI` from `@tanstack/form-core` and returned from `useForm`
24 */
25export interface ReactFormApi<
26 in out TFormData,
27 in out TOnMount extends undefined | FormValidateOrFn<TFormData>,
28 in out TOnChange extends undefined | FormValidateOrFn<TFormData>,
29 in out TOnChangeAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
30 in out TOnBlur extends undefined | FormValidateOrFn<TFormData>,
31 in out TOnBlurAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
32 in out TOnSubmit extends undefined | FormValidateOrFn<TFormData>,
33 in out TOnSubmitAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
34 in out TOnDynamic extends undefined | FormValidateOrFn<TFormData>,
35 in out TOnDynamicAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
36 in out TOnServer extends undefined | FormAsyncValidateOrFn<TFormData>,
37 in out TSubmitMeta,
38> {
39 /**
40 * A React component to render form fields. With this, you can render and manage individual form fields.
41 */
42 Field: FieldComponent<
43 TFormData,
44 TOnMount,
45 TOnChange,
46 TOnChangeAsync,
47 TOnBlur,
48 TOnBlurAsync,
49 TOnSubmit,
50 TOnSubmitAsync,
51 TOnDynamic,
52 TOnDynamicAsync,
53 TOnServer,
54 TSubmitMeta
55 >
56 FormGroup: FormGroupComponent<
57 TFormData,
58 TOnMount,
59 TOnChange,
60 TOnChangeAsync,
61 TOnBlur,
62 TOnBlurAsync,
63 TOnSubmit,
64 TOnSubmitAsync,
65 TOnDynamic,
66 TOnDynamicAsync,
67 TOnServer,
68 TSubmitMeta
69 >
70 /**
71 * A `Subscribe` function that allows you to listen and react to changes in the form's state. It's especially useful when you need to execute side effects or render specific components in response to state updates.
72 */
73 Subscribe: <
74 TSelected = NoInfer<
75 FormState<
76 TFormData,
77 TOnMount,
78 TOnChange,
79 TOnChangeAsync,
80 TOnBlur,
81 TOnBlurAsync,
82 TOnSubmit,
83 TOnSubmitAsync,
84 TOnDynamic,
85 TOnDynamicAsync,
86 TOnServer
87 >
88 >,
89 >(props: {
90 selector?: (
91 state: NoInfer<
92 FormState<
93 TFormData,
94 TOnMount,
95 TOnChange,
96 TOnChangeAsync,
97 TOnBlur,
98 TOnBlurAsync,
99 TOnSubmit,
100 TOnSubmitAsync,
101 TOnDynamic,
102 TOnDynamicAsync,
103 TOnServer
104 >
105 >,
106 ) => TSelected
107 children: ((state: NoInfer<TSelected>) => ReactNode) | ReactNode
108 }) => ReturnType<FunctionComponent>
110​
111/**
112 * An extended version of the `FormApi` class that includes React-specific functionalities from `ReactFormApi`
113 */
114export type ReactFormExtendedApi<
115 TFormData,
116 TOnMount extends undefined | FormValidateOrFn<TFormData>,
117 TOnChange extends undefined | FormValidateOrFn<TFormData>,
118 TOnChangeAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
119 TOnBlur extends undefined | FormValidateOrFn<TFormData>,
120 TOnBlurAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
121 TOnSubmit extends undefined | FormValidateOrFn<TFormData>,
122 TOnSubmitAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
123 TOnDynamic extends undefined | FormValidateOrFn<TFormData>,
124 TOnDynamicAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
125 TOnServer extends undefined | FormAsyncValidateOrFn<TFormData>,
126 TSubmitMeta,
127> = FormApi<
128 TFormData,
129 TOnMount,
130 TOnChange,
131 TOnChangeAsync,
132 TOnBlur,
133 TOnBlurAsync,
134 TOnSubmit,
135 TOnSubmitAsync,
136 TOnDynamic,
137 TOnDynamicAsync,
138 TOnServer,
139 TSubmitMeta
140> &
141 ReactFormApi<
142 TFormData,
143 TOnMount,
144 TOnChange,
145 TOnChangeAsync,
146 TOnBlur,
147 TOnBlurAsync,
148 TOnSubmit,
149 TOnSubmitAsync,
150 TOnDynamic,
151 TOnDynamicAsync,
152 TOnServer,
153 TSubmitMeta
154 >
155​
156function LocalSubscribe({
157 form,
158 selector = (state) => state,
159 children,
160}: PropsWithChildren<{
161 form: AnyFormApi
162 selector?: (state: AnyFormState) => AnyFormState
163}>): ReturnType<FunctionComponent> {
164 const data = useSelector(form.store, selector)
165​
166 return <>{functionalUpdate(children, data)}</>
168​
169/**
170 * A custom React Hook that returns an extended instance of the `FormApi` class.
171 *
172 * This API encapsulates all the necessary functionalities related to the form. It allows you to manage form state, handle submissions, and interact with form fields
173 */
174export function useForm<
175 TFormData,
176 TOnMount extends undefined | FormValidateOrFn<TFormData>,
177 TOnChange extends undefined | FormValidateOrFn<TFormData>,
178 TOnChangeAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
179 TOnBlur extends undefined | FormValidateOrFn<TFormData>,
180 TOnBlurAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
181 TOnSubmit extends undefined | FormValidateOrFn<TFormData>,
182 TOnSubmitAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
183 TOnDynamic extends undefined | FormValidateOrFn<TFormData>,
184 TOnDynamicAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
185 TOnServer extends undefined | FormAsyncValidateOrFn<TFormData>,
186 TSubmitMeta,
187>(
188 opts?: FormOptions<
189 TFormData,
190 TOnMount,
191 TOnChange,
192 TOnChangeAsync,
193 TOnBlur,
194 TOnBlurAsync,
195 TOnSubmit,
196 TOnSubmitAsync,
197 TOnDynamic,
198 TOnDynamicAsync,
199 TOnServer,
200 TSubmitMeta
201 >,
202) {
203 const fallbackFormId = useFormId()
204 const [prevFormId, setPrevFormId] = useState<string>(opts?.formId as never)
205​
206 const [formApi, setFormApi] = useState(() => {
207 return new FormApi<
208 TFormData,
209 TOnMount,
210 TOnChange,
211 TOnChangeAsync,
212 TOnBlur,
213 TOnBlurAsync,
214 TOnSubmit,
215 TOnSubmitAsync,
216 TOnDynamic,
217 TOnDynamicAsync,
218 TOnServer,
219 TSubmitMeta
220 >({ ...opts, formId: opts?.formId ?? fallbackFormId })
221 })
222​
223 if (prevFormId !== opts?.formId) {
224 const formId = opts?.formId ?? fallbackFormId
225 setFormApi(new FormApi({ ...opts, formId }))
226 setPrevFormId(formId)
227 }
228​
229 const extendedFormApi = useMemo(() => {
230 const extendedApi: ReactFormExtendedApi<
231 TFormData,
232 TOnMount,
233 TOnChange,
234 TOnChangeAsync,
235 TOnBlur,
236 TOnBlurAsync,
237 TOnSubmit,
238 TOnSubmitAsync,
239 TOnDynamic,
240 TOnDynamicAsync,
241 TOnServer,
242 TSubmitMeta
243 > = {
244 ...formApi,
245 handleSubmit: ((...props: never[]) => {
246 return formApi._handleSubmit(...props)
247 }) as typeof formApi.handleSubmit,
248 // We must add all `get`ters from `core`'s `FormApi` here, as otherwise the spread operator won't catch those
249 get formId(): string {
250 return formApi._formId
251 },
252 get state() {
253 return formApi.store.state
254 },
255 } as never
256​
257 extendedApi.Field = function APIField(props) {
258 return <Field {...props} form={formApi} />
259 }
260​
261 extendedApi.FormGroup = function APIFormGroup(props) {
262 return <FormGroup {...props} form={formApi} />
263 }
264​
265 extendedApi.Subscribe = function Subscribe(props: any) {
266 return (
267 <LocalSubscribe
268 form={formApi}
269 selector={props.selector}
270 children={props.children}
271 />
272 )
273 }
274​
275 return extendedApi
276 }, [formApi])
277​
278 useIsomorphicLayoutEffect(formApi.mount, [])
279​
280 /**
281 * formApi.update should not have any side effects. Think of it like a `useRef`
282 * that we need to keep updated every render with the most up-to-date information.
283 */
284 useIsomorphicLayoutEffect(() => {
285 formApi.update(opts)
286 })
287​
288 const hasRan = useRef(false)
289​
290 useIsomorphicLayoutEffect(() => {
291 if (!hasRan.current) return
292 if (!opts?.transform) return
293 mergeAndUpdate(formApi, opts.transform as never)
294 }, [formApi, opts?.transform])
295​
296 useIsomorphicLayoutEffect(() => {
297 hasRan.current = true
298 })
299​
300 return extendedFormApi