Skip to content

Commit

Permalink
fix: Field default should now be set properly (#445)
Browse files Browse the repository at this point in the history
* fix: fields should now set default value properly

* test: add test to validate fix
  • Loading branch information
crutchcorn committed Sep 7, 2023
1 parent 6ffa574 commit d80bcf7
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 18 deletions.
29 changes: 11 additions & 18 deletions packages/form-core/src/FieldApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export class FieldApi<TData, TFormData> {

this.state = this.store.state
this.prevState = this.state
this.update(opts as never)
this.options = opts as never
}

mount = () => {
Expand All @@ -151,6 +151,7 @@ export class FieldApi<TData, TFormData> {
})
})

this.update(this.options as never)
this.options.onMount?.(this as never)

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

update = (opts: FieldApiOptions<typeof this._tdata, TFormData>) => {
this.options = {
asyncDebounceMs: this.form.options.asyncDebounceMs ?? 0,
...opts,
} as never

// Default Value
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (this.state.value === undefined) {
if (this.options.defaultValue !== undefined) {
this.setValue(this.options.defaultValue as never)
} else if (
opts.form.options.defaultValues?.[
this.options.name as keyof TFormData
] !== undefined
) {
this.setValue(
opts.form.options.defaultValues[
this.options.name as keyof TFormData
] as never,
)
const formDefault =
opts.form.options.defaultValues?.[opts.name as keyof TFormData]

if (opts.defaultValue !== undefined) {
this.setValue(opts.defaultValue as never)
} else if (formDefault !== undefined) {
this.setValue(formDefault as never)
}
}

// Default Meta
if (this._getMeta() === undefined) {
this.setMeta(this.state.meta)
}

this.options = opts as never
}

getValue = (): typeof this._tdata => {
Expand Down
17 changes: 17 additions & 0 deletions packages/form-core/src/tests/FieldApi.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -433,4 +433,21 @@ describe('field api', () => {
await vi.runAllTimersAsync()
expect(field.getMeta().error).toBe('Please enter a different value')
})

it('should handle default value on field using state.value', async () => {
interface Form {
name: string
}
const form = new FormApi<Form>()

const field = new FieldApi({
form,
name: 'name',
defaultValue: 'test',
})

field.mount()

expect(field.state.value).toBe('test')
})
})

0 comments on commit d80bcf7

Please sign in to comment.