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

ReactFormApi.lib.tsx

70 lines2.1 KB

1import { InternalFormApi } from '@tanstack/form-core/internals'
2import * as React from 'react'
3import { useEffect, useRef } from 'react'
4import {
5 createArrayFieldComponent,
6 createFieldComponent,
7 createFormGroupComponent,
8 createSubscribeComponent,
9} from './Components.lib'
10import type { DefaultOptions, FormOptions } from '@tanstack/form-core'
11import type { ReactTanStackFormComponents } from './Components.public'
12​
13const useReactId =
14 (React as typeof React & { useId?: () => string }).useId ?? (() => undefined)
15​
16export class InternalReactFormApi
17 extends InternalFormApi<any, any, any>
18 implements ReactTanStackFormComponents<any, any, any>
20 Field: ReactTanStackFormComponents<any, any, any>['Field']
21 ArrayField: ReactTanStackFormComponents<any, any, any>['ArrayField']
22 Subscribe: ReactTanStackFormComponents<any, any, any>['Subscribe']
23 FormGroup: ReactTanStackFormComponents<any, any, any>['FormGroup']
24​
25 constructor(
26 options: FormOptions<any, any, any, unknown>,
27 defaultOptions?: DefaultOptions,
28 ) {
29 super(options, defaultOptions)
30 this.Field = createFieldComponent(
31 this,
32 'field',
33 ) as InternalReactFormApi['Field']
34 this.ArrayField = createArrayFieldComponent(this, 'field')
35 this.Subscribe = createSubscribeComponent(this)
36 this.FormGroup = createFormGroupComponent(
37 this,
38 ) as InternalReactFormApi['FormGroup']
39 }
41​
42export function initializeForm(
43 options: FormOptions<any, any, any, unknown>,
44): InternalReactFormApi {
45 return new InternalReactFormApi(options)
47​
48export function useInternalForm(
49 options: FormOptions<any, any, any, unknown>,
50 initializeFn: (
51 options: FormOptions<any, any, any, unknown>,
52 ) => InternalReactFormApi,
53) {
54 const reactFormId = useReactId()
55 const resolvedOptions =
56 options.formId === undefined ? { ...options, formId: reactFormId } : options
57 const formRef = useRef<InternalReactFormApi>(null)
58​
59 if (!formRef.current) {
60 formRef.current = initializeFn(resolvedOptions)
61 }
62​
63 useEffect(() => formRef.current!._update(resolvedOptions))
64 useEffect(() => {
65 const unmount = formRef.current!.mount()
66 return unmount
67 }, [])
68​
69 return formRef.current