Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 110 additions & 23 deletions packages/react-form/src/useField.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
'use client'

import { useMemo, useRef } from 'react'
import { useMemo, useRef, useState } from 'react'
import { useStore } from '@tanstack/react-store'
import { FieldApi, functionalUpdate } from '@tanstack/form-core'
import { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect'
import type {
AnyFieldApi,
AnyFieldMeta,
DeepKeys,
DeepValue,
FieldAsyncValidateOrFn,
Expand Down Expand Up @@ -195,17 +197,103 @@ export function useField<
) {
// Keep a snapshot of options so that React Compiler doesn't
// wrongly optimize fieldApi.
const optsRef = useRef(opts)
optsRef.current = opts
const [prevOptions, setPrevOptions] = useState(() => ({
form: opts.form,
name: opts.name,
}))

const fieldApi = useMemo(() => {
const api = new FieldApi({
...optsRef.current,
form: opts.form,
name: opts.name,
const [fieldApi, setFieldApi] = useState(() => {
return new FieldApi({
...opts,
})
})

// We only want to
// update on name changes since those are at risk of becoming stale. The field
// state must be up to date for the internal JSX render.
// The other options can freely be in `fieldApi.update`
if (prevOptions.form !== opts.form || prevOptions.name !== opts.name) {
setFieldApi(
new FieldApi({
...opts,
}),
)
setPrevOptions({ form: opts.form, name: opts.name })
}

const reactiveStateValue = useStore(fieldApi.store, (state) => state.value)
const reactiveMetaIsTouched = useStore(
fieldApi.store,
(state) => state.meta.isTouched,
)
const reactiveMetaIsBlurred = useStore(
fieldApi.store,
(state) => state.meta.isBlurred,
)
const reactiveMetaIsDirty = useStore(
fieldApi.store,
(state) => state.meta.isDirty,
)
const reactiveMetaErrorMap = useStore(
fieldApi.store,
(state) => state.meta.errorMap,
)
const reactiveMetaErrorSourceMap = useStore(
fieldApi.store,
(state) => state.meta.errorSourceMap,
)
const reactiveMetaIsValidating = useStore(
fieldApi.store,
(state) => state.meta.isValidating,
)

// This makes me sad, but if I understand correctly, this is what we have to do for reactivity to work properly with React compiler.
const extendedFieldApi = useMemo(() => {
const reactiveFieldApi = {
...fieldApi,
get state() {
return {
value: reactiveStateValue,
get meta() {
return {
...fieldApi.state.meta,
isTouched: reactiveMetaIsTouched,
isBlurred: reactiveMetaIsBlurred,
isDirty: reactiveMetaIsDirty,
errorMap: reactiveMetaErrorMap,
errorSourceMap: reactiveMetaErrorSourceMap,
isValidating: reactiveMetaIsValidating,
} satisfies AnyFieldMeta
},
} satisfies AnyFieldApi['state']
},
}

const extendedApi: typeof api &
const extendedApi: FieldApi<
TParentData,
TName,
TData,
TOnMount,
TOnChange,
TOnChangeAsync,
TOnBlur,
TOnBlurAsync,
TOnSubmit,
TOnSubmitAsync,
TOnDynamic,
TOnDynamicAsync,
TFormOnMount,
TFormOnChange,
TFormOnChangeAsync,
TFormOnBlur,
TFormOnBlurAsync,
TFormOnSubmit,
TFormOnSubmitAsync,
TFormOnDynamic,
TFormOnDynamicAsync,
TFormOnServer,
TPatentSubmitMeta
> &
ReactFieldApi<
TParentData,
TFormOnMount,
Expand All @@ -219,16 +307,21 @@ export function useField<
TFormOnDynamicAsync,
TFormOnServer,
TPatentSubmitMeta
> = api as never
> = reactiveFieldApi as never

extendedApi.Field = Field as never

return extendedApi
// We only want to
// update on name changes since those are at risk of becoming stale. The field
// state must be up to date for the internal JSX render.
// The other options can freely be in `fieldApi.update`
}, [opts.form, opts.name])
}, [
fieldApi,
reactiveStateValue,
reactiveMetaIsTouched,
reactiveMetaIsBlurred,
reactiveMetaIsDirty,
reactiveMetaErrorMap,
reactiveMetaErrorSourceMap,
reactiveMetaIsValidating,
])

useIsomorphicLayoutEffect(fieldApi.mount, [fieldApi])

Expand All @@ -252,7 +345,7 @@ export function useField<
: undefined,
)

return fieldApi
return extendedFieldApi
}

/**
Expand Down Expand Up @@ -655,13 +748,7 @@ export const Field = (<

const jsxToDisplay = useMemo(
() => functionalUpdate(children, fieldApi as any),
/**
* The reason this exists is to fix an issue with the React Compiler.
* Namely, functionalUpdate is memoized where it checks for `fieldApi`, which is a static type.
* This means that when `state.value` changes, it does not trigger a re-render. The useMemo explicitly fixes this problem
*/
// eslint-disable-next-line react-hooks/exhaustive-deps
[children, fieldApi, fieldApi.state.value, fieldApi.state.meta],
[children, fieldApi],
)
return (<>{jsxToDisplay}</>) as never
}) satisfies FunctionComponent<
Expand Down
5 changes: 3 additions & 2 deletions packages/react-form/tests/useForm.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -909,8 +909,9 @@ describe('useForm', () => {
<>
<form.Field name="foo" mode="array">
{(arrayField) =>
arrayField.state.value.map((row, i) => (
<form.Field key={row.id} name={`foo[${i}].name`}>
arrayField.state.value.map((_, i) => (
// eslint-disable-next-line @eslint-react/no-array-index-key
<form.Field key={i} name={`foo[${i}].name`}>
{(field) => {
expect(field.name).toBe(`foo[${i}].name`)
expect(field.state.value).not.toBeUndefined()
Expand Down
Loading