Skip to content
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

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

Closed
crutchcorn opened this issue Jun 27, 2024 · 0 comments · Fixed by #795
Closed

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

crutchcorn opened this issue Jun 27, 2024 · 0 comments · Fixed by #795

Comments

@crutchcorn
Copy link
Member

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant