Skip to content
Source
Sign inSign up
TanStack/form
Open History to see the last commit

form.tsx

56 lines1.5 KB

1import { createServerFn } from '@tanstack/react-start'
2import {
3 ServerValidateError,
4 createServerValidate,
5 getFormData,
6} from '@tanstack/react-form/start'
7import { setResponseStatus } from '@tanstack/react-start/server'
8import { formOpts } from './form-isomorphic'
9​
10const serverValidate = createServerValidate({
11 ...formOpts,
12 onServerValidate: ({ value }) => {
13 if (value.age < 12) {
14 return 'Server validation: You must be at least 12 to sign up'
15 }
16 },
17})
18​
19export const handleForm = createServerFn({
20 method: 'POST',
21})
22 .validator((data: unknown) => {
23 if (!(data instanceof FormData)) {
24 throw new Error('Invalid form data')
25 }
26 return data
27 })
28 .handler(async (ctx) => {
29 try {
30 const validatedData = await serverValidate(ctx.data)
31 console.log('validatedData', validatedData)
32 // Persist the form data to the database
33 // await sql`
34 // INSERT INTO users (name, email, password)
35 // VALUES (${validatedData.name}, ${validatedData.email}, ${validatedData.password})
36 // `
37 } catch (e) {
38 if (e instanceof ServerValidateError) {
39 // Log form errors or do any other logic here
40 return e.response
41 }
42​
43 // Some other error occurred when parsing the form
44 console.error(e)
45 setResponseStatus(500)
46 return 'There was an internal error'
47 }
48​
49 return 'Form has validated successfully'
50 })
51​
52export const getFormDataFromServer = createServerFn({ method: 'GET' }).handler(
53 async () => {
54 return getFormData()
55 },