Open History to see the last commit
1import { createServerFn } from '@tanstack/start'
2import { formOptions } from '@tanstack/react-form'
3import {
4 ServerValidateError,
5 createServerValidate,
6 getFormData,
7} from '@tanstack/react-form/start'
8β
9export const formOpts = formOptions({
10 defaultValues: {
11 firstName: '',
12 age: 0,
13 },
14})
15β
16const serverValidate = createServerValidate({
17 ...formOpts,
18 onServerValidate: ({ value }) => {
19 if (value.age < 12) {
20 return 'Server validation: You must be at least 12 to sign up'
21 }
22 },
23})
24β
25export const handleForm = createServerFn(
26 'POST',
27 async (formData: FormData, ctx) => {
28 try {
29 await serverValidate(ctx, formData)
30 } catch (e) {
31 if (e instanceof ServerValidateError) {
32 return e.response
33 }
34β
35 // Some other error occurred when parsing the form
36 console.error(e)
37 return new Response('There was an internal error', {
38 status: 500,
39 })
40 }
41β
42 return new Response('Form has validated successfully', {
43 status: 200,
44 })
45 },
46)
47β
48export const getFormDataFromServer = createServerFn('GET', async (_, ctx) => {
49 return getFormData(ctx)
50})