Open History to see the last commit
1import { useSelector } from '@tanstack/vue-store'
2import { onMounted, onUnmounted, shallowRef, watch, watchEffect } from 'vue'
3import type { ShallowRef } from 'vue'
4import type {
5 AnyInternalFieldApi,
6 AnyInternalFormApi,
7} from '@tanstack/form-core/internals'
8β
9export interface InternalFieldProps {
10 form: AnyInternalFormApi
11 name: string
12 [key: string]: unknown
13}
14β
15export function useField(
16 options: () => InternalFieldProps,
17): ShallowRef<AnyInternalFieldApi> {
18 const initialOptions = options()
19 const resetVersion = useSelector(initialOptions.form._atoms.resetVersion)
20β
21 const createField = () => {
22 const current = options()
23 return current.form._getOrCreateFieldApi(
24 {
25 ...current,
26 name: current.name,
27 } as never,
28 'field',
29 )
30 }
31β
32 const fieldApi = shallowRef(createField())
33β
34 watch(
35 [() => options().form, () => options().name, resetVersion],
36 () => {
37 fieldApi.value = createField()
38 },
39 { flush: 'sync' },
40 )
41β
42 watchEffect(() => {
43 fieldApi.value._update(options() as never, 'field')
44 })
45β
46 let mounted = false
47 let unregister: (() => void) | undefined
48 watch(
49 fieldApi,
50 (field) => {
51 if (!mounted) return
52 unregister?.()
53 unregister = field._register()
54 },
55 { flush: 'sync' },
56 )
57 onMounted(() => {
58 mounted = true
59 unregister = fieldApi.value._register()
60 })
61 onUnmounted(() => unregister?.())
62β
63 return fieldApi
64}