Skip to content

Commit d80bcf7

Browse files
authored
fix: Field default should now be set properly (#445)
* fix: fields should now set default value properly * test: add test to validate fix
1 parent 6ffa574 commit d80bcf7

File tree

2 files changed

+28
-18
lines changed

2 files changed

+28
-18
lines changed

packages/form-core/src/FieldApi.ts

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ export class FieldApi<TData, TFormData> {
129129

130130
this.state = this.store.state
131131
this.prevState = this.state
132-
this.update(opts as never)
132+
this.options = opts as never
133133
}
134134

135135
mount = () => {
@@ -151,6 +151,7 @@ export class FieldApi<TData, TFormData> {
151151
})
152152
})
153153

154+
this.update(this.options as never)
154155
this.options.onMount?.(this as never)
155156

156157
return () => {
@@ -163,33 +164,25 @@ export class FieldApi<TData, TFormData> {
163164
}
164165

165166
update = (opts: FieldApiOptions<typeof this._tdata, TFormData>) => {
166-
this.options = {
167-
asyncDebounceMs: this.form.options.asyncDebounceMs ?? 0,
168-
...opts,
169-
} as never
170-
171167
// Default Value
172168
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
173169
if (this.state.value === undefined) {
174-
if (this.options.defaultValue !== undefined) {
175-
this.setValue(this.options.defaultValue as never)
176-
} else if (
177-
opts.form.options.defaultValues?.[
178-
this.options.name as keyof TFormData
179-
] !== undefined
180-
) {
181-
this.setValue(
182-
opts.form.options.defaultValues[
183-
this.options.name as keyof TFormData
184-
] as never,
185-
)
170+
const formDefault =
171+
opts.form.options.defaultValues?.[opts.name as keyof TFormData]
172+
173+
if (opts.defaultValue !== undefined) {
174+
this.setValue(opts.defaultValue as never)
175+
} else if (formDefault !== undefined) {
176+
this.setValue(formDefault as never)
186177
}
187178
}
188179

189180
// Default Meta
190181
if (this._getMeta() === undefined) {
191182
this.setMeta(this.state.meta)
192183
}
184+
185+
this.options = opts as never
193186
}
194187

195188
getValue = (): typeof this._tdata => {

packages/form-core/src/tests/FieldApi.spec.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -433,4 +433,21 @@ describe('field api', () => {
433433
await vi.runAllTimersAsync()
434434
expect(field.getMeta().error).toBe('Please enter a different value')
435435
})
436+
437+
it('should handle default value on field using state.value', async () => {
438+
interface Form {
439+
name: string
440+
}
441+
const form = new FormApi<Form>()
442+
443+
const field = new FieldApi({
444+
form,
445+
name: 'name',
446+
defaultValue: 'test',
447+
})
448+
449+
field.mount()
450+
451+
expect(field.state.value).toBe('test')
452+
})
436453
})

0 commit comments

Comments
 (0)