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
5 changes: 5 additions & 0 deletions .changeset/null-field-default-value.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/form-core': patch
---

Treat field-level `defaultValue: null` as a valid default value instead of falling back to the form-level default when resolving `isDefaultValue` and in `resetField`.
11 changes: 7 additions & 4 deletions packages/form-core/src/FormApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1233,11 +1233,13 @@ export class FormApi<
// As primitives, we don't need to aggressively persist the same referential value for performance reasons
const isFieldValid = !isNonEmptyArray(fieldErrors)
const isFieldPristine = !currBaseMeta.isDirty
const fieldDefault =
this.getFieldInfo(fieldName).instance?.options.defaultValue
const isDefaultValue = evaluate(
curFieldVal,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
this.getFieldInfo(fieldName)?.instance?.options.defaultValue ??
getBy(this.options.defaultValues, fieldName),
fieldDefault !== undefined
? fieldDefault
: getBy(this.options.defaultValues, fieldName),
)

if (
Expand Down Expand Up @@ -2940,7 +2942,8 @@ export class FormApi<
const fieldDefault =
this.getFieldInfo(field).instance?.options.defaultValue
const formDefault = getBy(this.options.defaultValues, field)
const targetValue = fieldDefault ?? formDefault
const targetValue =
fieldDefault !== undefined ? fieldDefault : formDefault

return {
...prev,
Expand Down
36 changes: 36 additions & 0 deletions packages/form-core/tests/FieldApi.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,42 @@ describe('field api', () => {
expect(field.getMeta().isDefaultValue).toBe(true)
})

it('should treat field-level defaultValue of null as default when form default is non-null', () => {
const form = new FormApi({
defaultValues: {
name: 'test' as string | null,
},
})
form.mount()

const field = new FieldApi({
form,
name: 'name',
defaultValue: null,
})
field.mount()

expect(field.getValue()).toBe(null)
expect(field.getMeta().isDefaultValue).toBe(true)

field.setValue('other')
expect(field.getMeta().isDefaultValue).toBe(false)

field.setValue(null)
expect(field.getMeta().isDefaultValue).toBe(true)

form.resetField('name')
expect(field.getValue()).toBe(null)
expect(field.getMeta().isDefaultValue).toBe(true)

field.setValue('other')
expect(field.getMeta().isDefaultValue).toBe(false)

form.reset()
expect(field.getValue()).toBe(null)
expect(field.getMeta().isDefaultValue).toBe(true)
})

it('should be false when value is undefined and a default value is specified in form-level only', () => {
const form = new FormApi({
defaultValues: {
Expand Down