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 12 commits into
base: main
Choose a base branch
from
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 @@ -347,6 +347,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 @@ -626,5 +626,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 @@ -190,9 +190,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 @@ -210,12 +212,19 @@ export function useForm<

useStore(formApi.store, (state) => state.isSubmitting)

// 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)

/**
* formApi.update should not have any side effects. Think of it like a `useRef`
* that we need to keep updated every render with the most up-to-date information.
*/
useIsomorphicLayoutEffect(() => {
formApi.update(opts)
if (!evaluate(opts, stableOptsRef.current)) {
stableOptsRef.current = opts
formApi.update(opts)
}
})

return formApi
Expand Down
125 changes: 125 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,129 @@ 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>

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

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

await user.click(changeProps)
await waitFor(() => expect(input).toHaveValue('props-change'))

// checks stableRef is comparing against previously set default
await user.click(changePropsAgain)
await waitFor(() => expect(input).toHaveValue('props-change-again'))
})
})
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'))
})
})