Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
16 changes: 16 additions & 0 deletions .changeset/fix-array-swap-rerender.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@tanstack/react-form': patch
---

fix(react-form): re-render mode="array" fields after swapValues/moveValue

When `swapValues` or `moveValue` was called on a `mode="array"` field, the
array field did not re-render because the array length didn't change and the
selector only tracked length (to avoid re-renders on child property changes,
see #1925).

The fix introduces a small version counter via `useReducer` that bumps
whenever `swapValues` or `moveValue` is called. This forces a re-render so
the displayed item order stays in sync with the form state.

Fixes #2018
32 changes: 31 additions & 1 deletion packages/react-form/src/useField.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client'

import { useMemo, useRef, useState } from 'react'
import { useMemo, useReducer, useRef, useState } from 'react'
import { useStore } from '@tanstack/react-store'
import { FieldApi, functionalUpdate } from '@tanstack/form-core'
import { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect'
Expand Down Expand Up @@ -221,6 +221,14 @@ export function useField<
setPrevOptions({ form: opts.form, name: opts.name })
}

// For array mode, track a version counter that bumps on structural operations
// (swapValues/moveValue) so re-orders trigger re-renders even when length stays the same.
// See: https://github.com/TanStack/form/issues/2018
const [arrayStructuralVersion, bumpArrayStructuralVersion] = useReducer(
(v: number) => v + 1,
0,
)

// For array mode, only track length changes to avoid re-renders when child properties change
// See: https://github.com/TanStack/form/issues/1925
const reactiveStateValue = useStore(
Expand Down Expand Up @@ -323,6 +331,26 @@ export function useField<

extendedApi.Field = Field as never

// Wrap swapValues and moveValue for mode="array" so that re-ordering
// triggers a re-render even when the array length doesn't change.
// See: https://github.com/TanStack/form/issues/2018
if (opts.mode === 'array') {
const originalSwapValues = extendedApi.swapValues.bind(extendedApi)
extendedApi.swapValues = (
...args: Parameters<typeof extendedApi.swapValues>
) => {
originalSwapValues(...args)
bumpArrayStructuralVersion()
}
const originalMoveValue = extendedApi.moveValue.bind(extendedApi)
extendedApi.moveValue = (
...args: Parameters<typeof extendedApi.moveValue>
) => {
originalMoveValue(...args)
bumpArrayStructuralVersion()
}
}

return extendedApi
}, [
fieldApi,
Expand All @@ -334,6 +362,8 @@ export function useField<
reactiveMetaErrorMap,
reactiveMetaErrorSourceMap,
reactiveMetaIsValidating,
arrayStructuralVersion,
bumpArrayStructuralVersion,
])

useIsomorphicLayoutEffect(fieldApi.mount, [fieldApi])
Expand Down
76 changes: 76 additions & 0 deletions packages/react-form/tests/useField.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1304,6 +1304,82 @@ describe('useField', () => {
expect(renderCount.arrayField).toBeGreaterThan(arrayFieldBeforeAdd)
})

it('should rerender array field when swapValues or moveValue is called', async () => {
// Test for https://github.com/TanStack/form/issues/2018
// swapValues and moveValue don't change array length, but the displayed
// order should update — meaning the array field must re-render.
let arrayFieldRenderCount = 0

function Comp() {
const form = useForm({
defaultValues: {
fruits: ['apple', 'banana', 'cherry'],
},
})

return (
<form.Field name="fruits" mode="array">
{(field) => {
arrayFieldRenderCount++
return (
<div>
<ul data-testid="list">
{field.state.value.map((fruit, i) => (
<li key={i} data-testid={`item-${i}`}>
{fruit}
</li>
))}
</ul>
<button
type="button"
data-testid="swap"
onClick={() => field.swapValues(0, 2)}
>
Swap 0 and 2
</button>
<button
type="button"
data-testid="move"
onClick={() => field.moveValue(0, 1)}
>
Move 0 to 1
</button>
</div>
)
}}
</form.Field>
)
}

const { getByTestId } = render(
<StrictMode>
<Comp />
</StrictMode>,
)

const initialRender = arrayFieldRenderCount

// Swap first and last item — length stays the same but order changes
await user.click(getByTestId('swap'))

await waitFor(() => {
expect(arrayFieldRenderCount).toBeGreaterThan(initialRender)
expect(getByTestId('item-0')).toHaveTextContent('cherry')
expect(getByTestId('item-2')).toHaveTextContent('apple')
})

const afterSwapRender = arrayFieldRenderCount

// Move first item to index 1 — again, no length change
await user.click(getByTestId('move'))

await waitFor(() => {
expect(arrayFieldRenderCount).toBeGreaterThan(afterSwapRender)
expect(getByTestId('item-0')).toHaveTextContent('banana')
expect(getByTestId('item-1')).toHaveTextContent('cherry')
})
})

it('should handle defaultValue without setstate-in-render error', async () => {
// Spy on console.error before rendering
const consoleErrorSpy = vi.spyOn(console, 'error')
Expand Down
Loading