Open History to see the last commit
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>
21}
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
52}