Open History to see the last commit
1import { useEffect, useMemo, useRef } from 'preact/compat'
2import { useSelector } from '@tanstack/preact-store'
3import type { FunctionComponent } from 'preact/compat'
4import type {
5 AnyInternalFieldApi,
6 InternalFormApi,
7} from '@tanstack/form-core/internals'
8import type { PreactFormFieldProps } from './Components.public'
9β
10interface InternalFieldProps extends PreactFormFieldProps<
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 fieldComponents: Record<string, FunctionComponent<any>> | null,
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 'field',
40 )
41 if (fieldComponents === null) return field
42 Object.assign(field, fieldComponents)
43β
44 return field
45 }, [options.name, options.form, resetVersion, fieldComponents])
46β
47 useEffect(() => fieldApi._update(options, 'field'))
48β
49 useEffect(() => {
50 const cleanup = fieldApi._register()
51 return cleanup
52 }, [fieldApi])
53β
54 return fieldApi
55}