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