Skip to content

Handling Submissions

TanStack Form handles validation and state management for you. You can use any query library or async function to submit your data, as long as you await the result in onSubmit. The following example uses a TanStack Query mutation:

tsx
import { useForm } from '@tanstack/react-form'
import { useMutation } from '@tanstack/react-query'

function Example() {
  const saveMutation = useMutation({
    mutationFn: saveProfile,
  })

  const form = useForm({
    defaultValues: { firstName: '', lastName: '' },
    // Access the form values and an
    // abort signal to pass to a fetch request.
    onSubmit: async ({ value, signal }) => {
      await saveMutation.mutateAsync(value)
    },
  })

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault()
        e.stopPropagation()
        // Runtime errors or `onSubmit` rejections should be caught
        void form.handleSubmit().catch(console.error)
      }}
    >
      <button type="submit">Submit</button>
    </form>
  )
}

Linking the button to the form

A submit button usually submits the form element that contains it. You can also link it to a form with the form attribute:

tsx
<>
  <form
    id={form.formId}
    onSubmit={() => {
      /* ... */
    }}
  >
    {/* ... */}
  </form>
  <button type="submit" form={form.formId}>
    Submit
  </button>
</>

Validating the form values

Any validators you define on a field or on the form run before onSubmit is called. If any validator fails, onSubmit will not be called.

If you're using schemas for validation, check the validator outputs guide.

ts
const form = useForm({
  defaultValues: { firstName: '', lastName: '' },
  validators: [
    {
      run: ({ value }) => {
        if (value.firstName.length === 0) {
          return 'Please enter a name.'
        }

        return undefined
      },
    },
  ],
  onSubmit: ({ value }) => saveProfile(value),
})

Using values

You can use either validatorOutputs or value for submission. However, do not read values from formApi.state.values. If you don't disable inputs during submission, a user may change them while the submission is in progress. The submission preserves the submitted values and uses them for validation.

Validating in onSubmit

Sometimes, the query you send can fail and report validation issues. For example, let's check whether a username is taken before saving a profile:

ts
const form = useForm({
  defaultValues: { username: '' },
  onSubmit: async ({ value }) => {
    const isTaken = await isUsernameTaken(value)
    // The user isn't told what the problem is.
    // Even worse, the form assumes the submission succeeded.
    // How do we fix this?
    if (isTaken) return

    await saveProfile(value)
  },
})

Instead of returning early, we can use the provided helper functions to return validation issues:

ts
const form = useForm({
  defaultValues: { username: '' },
  onSubmit: async ({
    value,
    createValidationError,
    createErrorMap,
    parseIssues,
  }) => {
    const isTaken = await isUsernameTaken(value)
    if (isTaken) {
      // Returning this error tells the form that the submission failed
      const error = createValidationError('Username is taken!')
      // `onSubmit` gets the same createErrorMap and parseIssues
      //  helpers as validators
      const errorMap = createErrorMap()
      const issues = parseIssues([])

      return error
    }

    return await saveProfile(value)
  },
})

Handling invalid submissions

There are several ways a submission can fail:

  • Validators return errors
  • onSubmit returns validation errors
  • A runtime error occurs

You can use the onSubmitInvalid callback to handle these submission failures.

Validation failures

Validation failures call onSubmitInvalid with reason: 'validation':

ts
const form = useForm({
  defaultValues: { username: '' },
  validators: [/* ... */],
  onSubmit: () => {
    /* ... */
  },
  onSubmitInvalid: (context) => {
    if (context.reason !== 'validation') return

    // `source` identifies whether validation
    // failed in validators or `onSubmit`.
    void context.source

    // For example, you can focus the first invalid input element.
    document.querySelector<HTMLElement>('[aria-invalid="true"]')?.focus()
  },
})

Reuse submission handlers

If you handle invalid submissions the same way across your forms, configure a default onSubmitInvalid handler. See Default Options.

Runtime errors

If your query library uses promises, those promises might reject. By default, TanStack Form will not catch these rejections for you. You'll have to handle the rejected form.handleSubmit() promise yourself.

Before the form.handleSubmit() promise rejects, the form calls onSubmitInvalid with reason: 'exception'. This callback lets you control how the error is handled:

ts
const form = useForm({
  defaultValues: { username: '' },
  onSubmit: () => {
    /* ... */
  },
  onSubmitInvalid: (context) => {
    if (context.reason !== 'exception') return

    // Prevent form.handleSubmit() from rejecting with this error.
    context.preventThrow()
    console.error('An error happened!', context.error)
  },
})