fix: onSubmit should now behave as expected

* fix: memoize all non-function form props by default

* chore: migrate useStableFormOpts to useMemo

* fix: options passed to useField will not always cause a re-render

* chore: minor code cleanups

* test: add previously failing test to demonstrate fix

* chore: fix linting

* fix: running form.update repeatedly should not wipe form state

* test: add test to validate formapi update behavior

* test: add initial tests for useStableOptions

* chore: remove useStableOpts and useFormCallback
This commit is contained in:
Corbin Crutchley
2023-09-06 19:33:52 -07:00
committed by GitHub
parent 9424ed94f8
commit 6f76feee6b
11 changed files with 171 additions and 60 deletions

View File

@@ -13,12 +13,9 @@ import { useForm } from '@tanstack/react-form'
export default function App() { export default function App() {
const form = useForm({ const form = useForm({
// Memoize your default values to prevent re-renders // Memoize your default values to prevent re-renders
defaultValues: React.useMemo( defaultValues: {
() => ({ fullName: '',
fullName: '', },
}),
[],
),
onSubmit: async (values) => { onSubmit: async (values) => {
// Do something with form data // Do something with form data
console.log(values) console.log(values)

View File

@@ -44,14 +44,10 @@ function FieldInfo({ field }: { field: FieldApi<any, any> }) {
export default function App() { export default function App() {
const form = useForm({ const form = useForm({
// Memoize your default values to prevent re-renders defaultValues: {
defaultValues: React.useMemo( firstName: '',
() => ({ lastName: '',
firstName: '', },
lastName: '',
}),
[],
),
onSubmit: async (values) => { onSubmit: async (values) => {
// Do something with form data // Do something with form data
console.log(values) console.log(values)

View File

@@ -17,13 +17,10 @@ function FieldInfo({ field }: { field: FieldApi<any, any> }) {
export default function App() { export default function App() {
const form = useForm({ const form = useForm({
// Memoize your default values to prevent re-renders // Memoize your default values to prevent re-renders
defaultValues: React.useMemo( defaultValues: {
() => ({ firstName: "",
firstName: "", lastName: "",
lastName: "", },
}),
[],
),
onSubmit: async (values) => { onSubmit: async (values) => {
// Do something with form data // Do something with form data
console.log(values); console.log(values);

View File

@@ -69,21 +69,20 @@ function getDefaultFormState<TData>(
defaultState: Partial<FormState<TData>>, defaultState: Partial<FormState<TData>>,
): FormState<TData> { ): FormState<TData> {
return { return {
values: {} as any, values: defaultState.values ?? ({} as never),
fieldMeta: {} as any, fieldMeta: defaultState.fieldMeta ?? ({} as never),
canSubmit: true, canSubmit: defaultState.canSubmit ?? true,
isFieldsValid: false, isFieldsValid: defaultState.isFieldsValid ?? false,
isFieldsValidating: false, isFieldsValidating: defaultState.isFieldsValidating ?? false,
isFormValid: false, isFormValid: defaultState.isFormValid ?? false,
isFormValidating: false, isFormValidating: defaultState.isFormValidating ?? false,
isSubmitted: false, isSubmitted: defaultState.isSubmitted ?? false,
isSubmitting: false, isSubmitting: defaultState.isSubmitting ?? false,
isTouched: false, isTouched: defaultState.isTouched ?? false,
isValid: false, isValid: defaultState.isValid ?? false,
isValidating: false, isValidating: defaultState.isValidating ?? false,
submissionAttempts: 0, submissionAttempts: defaultState.submissionAttempts ?? 0,
formValidationCount: 0, formValidationCount: defaultState.formValidationCount ?? 0,
...defaultState,
} }
} }
@@ -156,15 +155,18 @@ export class FormApi<TFormData> {
this.store.batch(() => { this.store.batch(() => {
const shouldUpdateValues = const shouldUpdateValues =
options.defaultValues && options.defaultValues &&
options.defaultValues !== this.options.defaultValues options.defaultValues !== this.options.defaultValues &&
!this.state.isTouched
const shouldUpdateState = const shouldUpdateState =
options.defaultState !== this.options.defaultState options.defaultState !== this.options.defaultState &&
!this.state.isTouched
this.store.setState(() => this.store.setState(() =>
getDefaultFormState( getDefaultFormState(
Object.assign( Object.assign(
{}, {},
this.state,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
shouldUpdateState ? options.defaultState : {}, shouldUpdateState ? options.defaultState : {},
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition

View File

@@ -213,4 +213,58 @@ describe('form api', () => {
expect(form.getFieldValue('names')).toStrictEqual(['one', 'three', 'two']) expect(form.getFieldValue('names')).toStrictEqual(['one', 'three', 'two'])
}) })
it('should not wipe values when updating', () => {
const form = new FormApi({
defaultValues: {
name: 'test',
},
})
form.setFieldValue('name', 'other')
expect(form.getFieldValue('name')).toEqual('other')
form.update()
expect(form.getFieldValue('name')).toEqual('other')
})
it('should wipe default values when not touched', () => {
const form = new FormApi({
defaultValues: {
name: 'test',
},
})
expect(form.getFieldValue('name')).toEqual('test')
form.update({
defaultValues: {
name: 'other',
},
})
expect(form.getFieldValue('name')).toEqual('other')
})
it('should not wipe default values when touched', () => {
const form = new FormApi({
defaultValues: {
name: 'one',
},
})
expect(form.getFieldValue('name')).toEqual('one')
form.setFieldValue('name', 'two', { touch: true })
form.update({
defaultValues: {
name: 'three',
},
})
expect(form.getFieldValue('name')).toEqual('two')
})
}) })

View File

@@ -1,9 +1,9 @@
/// <reference lib="dom" /> /// <reference lib="dom" />
import { render } from '@testing-library/react' import { render, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event' import userEvent from '@testing-library/user-event'
import '@testing-library/jest-dom' import '@testing-library/jest-dom'
import * as React from 'react' import * as React from 'react'
import { createFormFactory } from '..' import { createFormFactory, useForm } from '..'
const user = userEvent.setup() const user = userEvent.setup()
@@ -78,4 +78,50 @@ describe('useForm', () => {
expect(await findByText('FirstName')).toBeInTheDocument() expect(await findByText('FirstName')).toBeInTheDocument()
expect(queryByText('LastName')).not.toBeInTheDocument() expect(queryByText('LastName')).not.toBeInTheDocument()
}) })
it('should handle submitting properly', async () => {
function Comp() {
const [submittedData, setSubmittedData] = React.useState<{
firstName: string
} | null>(null)
const form = useForm({
defaultValues: {
firstName: 'FirstName',
},
onSubmit: (data) => {
setSubmittedData(data)
},
})
return (
<form.Provider>
<form.Field
name="firstName"
children={(field) => {
return (
<input
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
placeholder={'First name'}
/>
)
}}
/>
<button onClick={form.handleSubmit}>Submit</button>
{submittedData && <p>Submitted data: {submittedData.firstName}</p>}
</form.Provider>
)
}
const { findByPlaceholderText, getByText } = render(<Comp />)
const input = await findByPlaceholderText('First name')
await user.clear(input)
await user.type(input, 'OtherName')
await user.click(getByText('Submit'))
await waitFor(() =>
expect(getByText('Submitted data: OtherName')).toBeInTheDocument(),
)
})
}) })

View File

@@ -0,0 +1,8 @@
import type { FieldOptions } from '@tanstack/form-core'
export type UseFieldOptions<TData, TFormData> = FieldOptions<
TData,
TFormData
> & {
mode?: 'value' | 'array'
}

View File

@@ -1,5 +1,4 @@
import * as React from 'react' import React, { useState } from 'react'
//
import { useStore } from '@tanstack/react-store' import { useStore } from '@tanstack/react-store'
import type { import type {
DeepKeys, DeepKeys,
@@ -9,6 +8,8 @@ import type {
} from '@tanstack/form-core' } from '@tanstack/form-core'
import { FieldApi, functionalUpdate } from '@tanstack/form-core' import { FieldApi, functionalUpdate } from '@tanstack/form-core'
import { useFormContext, formContext } from './formContext' import { useFormContext, formContext } from './formContext'
import { useIsomorphicLayoutEffect } from './utils/useIsomorphicLayoutEffect'
import type { UseFieldOptions } from './types'
declare module '@tanstack/form-core' { declare module '@tanstack/form-core' {
// eslint-disable-next-line no-shadow // eslint-disable-next-line no-shadow
@@ -17,13 +18,6 @@ declare module '@tanstack/form-core' {
} }
} }
export type UseFieldOptions<TData, TFormData> = FieldOptions<
TData,
TFormData
> & {
mode?: 'value' | 'array'
}
export type UseField<TFormData> = <TField extends DeepKeys<TFormData>>( export type UseField<TFormData> = <TField extends DeepKeys<TFormData>>(
opts?: { name: Narrow<TField> } & UseFieldOptions< opts?: { name: Narrow<TField> } & UseFieldOptions<
DeepValue<TFormData, TField>, DeepValue<TFormData, TField>,
@@ -37,7 +31,7 @@ export function useField<TData, TFormData>(
// Get the form API either manually or from context // Get the form API either manually or from context
const { formApi, parentFieldName } = useFormContext() const { formApi, parentFieldName } = useFormContext()
const [fieldApi] = React.useState<FieldApi<TData, TFormData>>(() => { const [fieldApi] = useState<FieldApi<TData, TFormData>>(() => {
const name = ( const name = (
typeof opts.index === 'number' typeof opts.index === 'number'
? [parentFieldName, opts.index, opts.name] ? [parentFieldName, opts.index, opts.name]
@@ -53,8 +47,13 @@ export function useField<TData, TFormData>(
return api return api
}) })
// Keep options up to date as they are rendered /**
fieldApi.update({ ...opts, form: formApi } as never) * fieldApi.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(() => {
fieldApi.update({ ...opts, form: formApi } as never)
})
useStore( useStore(
fieldApi.store as any, fieldApi.store as any,
@@ -66,7 +65,7 @@ export function useField<TData, TFormData>(
) )
// Instantiates field meta and removes it when unrendered // Instantiates field meta and removes it when unrendered
React.useEffect(() => fieldApi.mount(), [fieldApi]) useIsomorphicLayoutEffect(() => fieldApi.mount(), [fieldApi])
return fieldApi return fieldApi
} }

View File

@@ -2,9 +2,10 @@ import type { FormState, FormOptions } from '@tanstack/form-core'
import { FormApi, functionalUpdate } from '@tanstack/form-core' import { FormApi, functionalUpdate } from '@tanstack/form-core'
import type { NoInfer } from '@tanstack/react-store' import type { NoInfer } from '@tanstack/react-store'
import { useStore } from '@tanstack/react-store' import { useStore } from '@tanstack/react-store'
import React from 'react' import React, { type ReactNode, useState } from 'react'
import { type UseField, type FieldComponent, Field, useField } from './useField' import { type UseField, type FieldComponent, Field, useField } from './useField'
import { formContext } from './formContext' import { formContext } from './formContext'
import { useIsomorphicLayoutEffect } from './utils/useIsomorphicLayoutEffect'
declare module '@tanstack/form-core' { declare module '@tanstack/form-core' {
// eslint-disable-next-line no-shadow // eslint-disable-next-line no-shadow
@@ -17,15 +18,13 @@ declare module '@tanstack/form-core' {
) => TSelected ) => TSelected
Subscribe: <TSelected = NoInfer<FormState<TFormData>>>(props: { Subscribe: <TSelected = NoInfer<FormState<TFormData>>>(props: {
selector?: (state: NoInfer<FormState<TFormData>>) => TSelected selector?: (state: NoInfer<FormState<TFormData>>) => TSelected
children: children: ((state: NoInfer<TSelected>) => ReactNode) | ReactNode
| ((state: NoInfer<TSelected>) => React.ReactNode)
| React.ReactNode
}) => any }) => any
} }
} }
export function useForm<TData>(opts?: FormOptions<TData>): FormApi<TData> { export function useForm<TData>(opts?: FormOptions<TData>): FormApi<TData> {
const [formApi] = React.useState(() => { const [formApi] = useState(() => {
// @ts-ignore // @ts-ignore
const api = new FormApi<TData>(opts) const api = new FormApi<TData>(opts)
@@ -58,9 +57,13 @@ export function useForm<TData>(opts?: FormOptions<TData>): FormApi<TData> {
formApi.useStore((state) => state.isSubmitting) formApi.useStore((state) => state.isSubmitting)
React.useEffect(() => { /**
* 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) formApi.update(opts)
}, [formApi, opts]) })
return formApi as any return formApi as any
} }

View File

@@ -0,0 +1,3 @@
/* c8 ignore start */
export const isBrowser = typeof window !== 'undefined'
/* c8 ignore end */

View File

@@ -0,0 +1,6 @@
/* c8 ignore start */
import { useEffect, useLayoutEffect } from 'react'
import { isBrowser } from './isBrowser'
export const useIsomorphicLayoutEffect = isBrowser ? useLayoutEffect : useEffect
/* c8 ignore end */