Skip to content

Migrate serverValidate from @tanstack/form/next to throw when errors occur #783

Closed
@crutchcorn

Description

@crutchcorn

Ideally the API should move from:

// action.ts
'use server'

// Notice the import path is different from the client
import { createServerValidate } from '@tanstack/react-form/nextjs'
import { formOpts } from './shared-code'

// Create the server action that will infer the types of the form from `formOpts`
const serverValidate = createServerValidate({
  ...formOpts,
  onServerValidate: ({ value }) => {
    if (value.age < 12) {
      return 'Server validation: You must be at least 12 to sign up'
    }
  },
})

export default async function someAction(prev: unknown, formData: FormData) {
  return await serverValidate(formData)
}

Which doesn't give a clear indication of when an error is validated or not to:

// action.ts
'use server'

// Notice the import path is different from the client
import { createServerValidate, ServerValidateError } from '@tanstack/react-form/nextjs'
import { formOpts } from './shared-code'

// Create the server action that will infer the types of the form from `formOpts`
const serverValidate = createServerValidate({
  ...formOpts,
  onServerValidate: ({ value }) => {
    if (value.age < 12) {
      return 'Server validation: You must be at least 12 to sign up'
    }
  },
})

export default async function someAction(prev: unknown, formData: FormData) {
  try {
    await serverValidate(formData)
  } catch (e) {
    if (e instanceof ServerValidateError) {
      return e.formState;
    }
  }
}

This makes it much more clear how to handle the next steps and error handling, encourages defensive behavior, and more.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions