Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/nine-beds-shout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/form-core': patch
---

Fix array async default values not updating
11 changes: 11 additions & 0 deletions packages/form-core/src/FormApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1512,6 +1512,17 @@ export class FormApi<
)
})

if (shouldUpdateValues) {
const helper = metaHelper(this)
for (const fieldKey of Object.keys(
this.fieldInfo,
) as DeepKeys<TFormData>[]) {
if (Array.isArray(this.getFieldValue(fieldKey))) {
helper.bumpArrayVersion(fieldKey)
}
}
}

formEventClient.emit('form-api', {
id: this._formId,
state: this.store.state,
Expand Down
38 changes: 38 additions & 0 deletions packages/react-form/tests/useField.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1526,6 +1526,44 @@ describe('useField', () => {
expect(getByTestId('item-1')).toHaveTextContent('John')
})

it('should rerender array field when async defaultValues resolve', async () => {
// Regression test for https://github.com/TanStack/form/issues/2178
// When async defaultValues arrive after initial render, array fields in
// mode="array" must re-render because _arrayVersion is used as the
// reactivity signal (not value length).
type Person = { name: string }
type FormData = { people: Person[] }

function Comp({ defaultValues }: { defaultValues?: FormData }) {
const form = useForm({ defaultValues })

return (
<form.Field name="people" mode="array">
{(field) => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const val = field.state.value ?? []
return (
<ol data-testid="list">
{val.map((person, i) => (
<li key={i} data-testid={`item-${i}`}>
{person.name}
</li>
))}
</ol>
)
}}
</form.Field>
)
}

const { getByTestId, rerender } = render(<Comp />)
expect(getByTestId('list').children).toHaveLength(0)

rerender(<Comp defaultValues={{ people: [{ name: 'Alice' }] }} />)
await waitFor(() => expect(getByTestId('list').children).toHaveLength(1))
expect(getByTestId('item-0')).toHaveTextContent('Alice')
})

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