Skip to content

fix(react): form.reset not working inside of onSubmit #1494

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
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
49 changes: 49 additions & 0 deletions packages/angular-form/tests/test.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -363,3 +363,52 @@ describe('TanStackFieldDirective', () => {
expect(getByText(onBlurError)).toBeInTheDocument()
})
})

describe('form should reset default value when resetting in onSubmit', () => {
it('should be able to handle async resets', async () => {
@Component({
selector: 'test-component',
standalone: true,
template: `
<ng-container [tanstackField]="form" name="name" #f="field">
<input
data-testid="fieldinput"
[value]="f.api.state.value"
(input)="f.api.handleChange($any($event).target.value)"
/>
</ng-container>
<button
type="button"
(click)="form.handleSubmit()"
data-testid="submit"
>
submit
</button>
`,
imports: [TanStackField],
})
class TestComponent {
form = injectForm({
defaultValues: {
name: '',
},
onSubmit: ({ value }) => {
expect(value).toEqual({ name: 'test' })
this.form.reset({ name: 'test' })
},
})
}

const { getByTestId } = await render(TestComponent)

const input = getByTestId('fieldinput')
const submit = getByTestId('submit')

await user.type(input, 'test')
await expect(input).toHaveValue('test')

await user.click(submit)

await expect(input).toHaveValue('test')
})
})
4 changes: 4 additions & 0 deletions packages/form-core/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,10 @@ export function evaluate<T>(objA: T, objB: T) {
return true
}

if (typeof objA === 'function' && typeof objB === 'function') {
return objA.toString() === objB.toString()
}

if (
typeof objA !== 'object' ||
objA === null ||
Expand Down
19 changes: 19 additions & 0 deletions packages/form-core/tests/FormApi.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,25 @@ describe('form api', () => {
})
})

it('form should reset default value when resetting in onSubmit', async () => {
const defaultValues = {
name: '',
}
const form = new FormApi({
defaultValues: defaultValues,
onSubmit: ({ value }) => {
form.reset(value)

expect(form.options.defaultValues).toMatchObject({
name: 'test',
})
},
})
form.mount()
form.setFieldValue('name', 'test')
form.handleSubmit()
})

it('should reset and set the new default values that are restored after an empty reset', () => {
const form = new FormApi({ defaultValues: { name: 'initial' } })
form.mount()
Expand Down
12 changes: 12 additions & 0 deletions packages/form-core/tests/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -562,5 +562,17 @@ describe('evaluate', () => {
{ test: { testTwo: '' }, arr: [[1]] },
)
expect(objComplexTrue).toEqual(true)

const funcTrue = evaluate(
{ test: () => console.log() },
{ test: () => console.log() },
)
expect(funcTrue).toEqual(true)

const funcFalse = evaluate(
{ test: () => console.log() },
{ test: () => console.warn() },
)
expect(funcFalse).toEqual(false)
})
})
15 changes: 12 additions & 3 deletions packages/react-form/src/useForm.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { FormApi, functionalUpdate } from '@tanstack/form-core'
import { FormApi, evaluate, functionalUpdate } from '@tanstack/form-core'
import { useStore } from '@tanstack/react-store'
import React, { useState } from 'react'
import { useRef, useState } from 'react'
import { Field } from './useField'
import { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect'
import type {
Expand Down Expand Up @@ -164,6 +164,13 @@ export function useForm<
TSubmitMeta
>,
) {
// stable reference of form options, needs to be tracked so form.update is only called
// when props are changed.
const stableOptsRef = useRef<typeof opts>(opts)
if (!evaluate(opts, stableOptsRef.current)) {
stableOptsRef.current = opts
}

const [formApi] = useState(() => {
const api = new FormApi<
TFormData,
Expand All @@ -190,9 +197,11 @@ export function useForm<
TOnServer,
TSubmitMeta
> = api as never

extendedApi.Field = function APIField(props) {
return <Field {...props} form={api} />
}

extendedApi.Subscribe = (props: any) => {
return (
<LocalSubscribe
Expand All @@ -216,7 +225,7 @@ export function useForm<
*/
useIsomorphicLayoutEffect(() => {
formApi.update(opts)
})
}, [stableOptsRef.current])
Copy link

@bpinto bpinto May 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given this value (stableOptsRef.current) is calculated on every re-render, I don't think using it as a [deps] adds any additional benefit over doing the check inside of the useIsomorphicLayoutEffect function.

  useIsomorphicLayoutEffect(() => {
    if (!evaluate(opts, stableOptsRef.current) {
      formApi.update(opts)
    }
  })

The reason for why I bring this up, is because I personally would rather avoid using a toString() to compare functions inside the evaluate function as that seems fragile/expensive. Therefore, there might be some alternative checks we could do here.

I don't know what the shouldUpdateReeval inside formApi.update() function is for but for the other 2 updates, if the form has been touched (!this.state.isTouched) then the update is skipped. So maybe there is something we can check to avoid the update() call altogether and potentially not need to deal with function toString() comparison.

  useIsomorphicLayoutEffect(() => {
    if (!formApi.form.state.isTouched) {
      formApi.update(opts)
    }
  })

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm... My concern here is that this issue only exists in the react sphere, all the other frameworks are working correctly, and modify core just to service a bug that only exists in react feels off.

I think I'll shelve this for a short minuet to look into other solutions, I appreciate the input.


return formApi
}
112 changes: 112 additions & 0 deletions packages/react-form/tests/useForm.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -794,4 +794,116 @@ describe('useForm', () => {

expect(fn).toHaveBeenCalledTimes(1)
})

it('form should reset default value when resetting in onSubmit', async () => {
function Comp() {
const form = useForm({
defaultValues: {
name: '',
},
onSubmit: ({ value }) => {
expect(value).toEqual({ name: 'another-test' })

form.reset(value)
},
})

return (
<form
onSubmit={(e) => {
e.preventDefault()
e.stopPropagation()
form.handleSubmit()
}}
>
<form.Field
name="name"
children={(field) => (
<input
data-testid="fieldinput"
name={field.name}
value={field.state.value}
onChange={(e) => field.handleChange(e.target.value)}
/>
)}
/>

<button type="submit" data-testid="submit">
submit
</button>

<button type="reset" data-testid="reset" onClick={() => form.reset()}>
Reset
</button>
</form>
)
}

const { getByTestId } = render(<Comp />)
const input = getByTestId('fieldinput')
const submit = getByTestId('submit')
const reset = getByTestId('reset')

await user.type(input, 'test')
await waitFor(() => expect(input).toHaveValue('test'))

await user.click(reset)
await waitFor(() => expect(input).toHaveValue(''))

await user.type(input, 'another-test')
await user.click(submit)
await waitFor(() => expect(input).toHaveValue('another-test'))
})

it('form should update when props are changed', async () => {
function Comp() {
const [defaultValue, setDefault] = useState<{
name: string
}>({ name: '' })

const form = useForm({
defaultValues: defaultValue,
onSubmit: ({ value }) => {
form.reset(value)
},
})

return (
<form
onSubmit={(e) => {
e.preventDefault()
e.stopPropagation()
form.handleSubmit()
}}
>
<form.Field
name="name"
children={(field) => (
<input
data-testid="fieldinput"
name={field.name}
value={field.state.value}
onChange={(e) => field.handleChange(e.target.value)}
/>
)}
/>

<button
type="button"
data-testid="change-props"
onClick={() => setDefault({ name: 'props-change' })}
>
change props
</button>
</form>
)
}

const { getByTestId } = render(<Comp />)
const input = getByTestId('fieldinput')
const changeProps = getByTestId('change-props')

await user.click(changeProps)
await waitFor(() => expect(input).toHaveValue('props-change'))
})
})
51 changes: 51 additions & 0 deletions packages/vue-form/tests/useForm.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -476,4 +476,55 @@ describe('useForm', () => {
await waitFor(() => getByText(error))
expect(getByText(error)).toBeInTheDocument()
})

it('form should reset default value when resetting in onSubmit', async () => {
const Comp = defineComponent(() => {
const form = useForm({
defaultValues: {
name: '',
},
onSubmit: ({ value }) => {
expect(value).toEqual({ name: 'test' })

form.reset({ name: 'test' })
},
})

return () => (
<div>
<form.Field name="name">
{({ field }: { field: AnyFieldApi }) => (
<input
data-testid="fieldinput"
name={field.name}
value={field.state.value}
onInput={(e) =>
field.handleChange((e.target as HTMLInputElement).value)
}
/>
)}
</form.Field>

<button
type="button"
onClick={() => form.handleSubmit()}
data-testid="submit"
>
submit
</button>
</div>
)
})

const { getByTestId } = render(<Comp />)
const input = getByTestId('fieldinput')
const submit = getByTestId('submit')

await user.type(input, 'test')
await waitFor(() => expect(input).toHaveValue('test'))

await user.click(submit)

await waitFor(() => expect(input).toHaveValue('test'))
})
})