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

useField.lib.ts

52 lines1.1 KB

1import { useEffect, useMemo, useRef } from 'react'
2import { useSelector } from '@tanstack/react-store'
3import type {
4 AnyInternalFieldApi,
5 FieldOptionsScope,
6 InternalFormApi,
7} from '@tanstack/form-core/internals'
8import type { ReactFormFieldProps } from './Components.public'
9​
10interface InternalFieldProps extends ReactFormFieldProps<
11 any,
12 any,
13 any,
14 any,
15 any,
16 any,
17 any,
18 any
19> {
20 form: InternalFormApi<any, any, any>
22​
23export function useField(
24 options: InternalFieldProps,
25 scope: FieldOptionsScope,
26): AnyInternalFieldApi {
27 const optionsRef = useRef(options)
28 optionsRef.current = options
29​
30 const resetVersion = useSelector(options.form._atoms.resetVersion)
31​
32 const fieldApi = useMemo(() => {
33 void resetVersion
34 const field = options.form._getOrCreateFieldApi(
35 {
36 ...optionsRef.current,
37 name: options.name,
38 },
39 scope,
40 )
41 return field
42 }, [options.name, options.form, resetVersion, scope])
43​
44 useEffect(() => fieldApi._update(options, scope))
45​
46 useEffect(() => {
47 const cleanup = fieldApi._register()
48 return cleanup
49 }, [fieldApi])
50​
51 return fieldApi