Open History to see the last commit
1---
2id: tanstack-start
3title: TanStack Form - TanStack Start
4---
5β
6## Using TanStack Form in TanStack Start
7β
8> Before reading this section, it's suggested you understand how TanStack `serverFunctions`. [Check out TanStack docs for more information](https://tanstack.com/start/latest/docs/framework/react/guide/server-functions)
9β
10### TanStack Start Prerequisites
11β
12- Start a new `TanStack Start` project, following the steps in the [TanStack Start Quickstart Guide](https://tanstack.com/router/latest/docs/framework/react/guide/tanstack-start)
13- Install `@tanstack/react-form-start`
14- Install any [form validator](./validation#validation-through-schema-libraries) of your choice. [Optional]
15β
16### Start integration
17β
18Let's start by creating a `formOption` that we'll use to share the form's shape across the client and server.
19β
20```tsx app/routes/index.tsx
21import { formOptions } from '@tanstack/react-form-start'
22β
23// You can pass other form options here
24export const formOpts = formOptions({
25 defaultValues: {
26 firstName: '',
27 age: 0,
28 },
29})
30```
31β
32Next, we can create [a Start Server Function](https://tanstack.com/start/latest/docs/framework/react/server-functions) that will handle the form submission on the server.
33β
34```tsx app/routes/index.tsx
35import {
36 createServerValidate,
37 ServerValidateError,
38} from '@tanstack/react-form-start'
39β
40const serverValidate = createServerValidate({
41 ...formOpts,
42 onServerValidate: ({ value }) => {
43 if (value.age < 12) {
44 return 'Server validation: You must be at least 12 to sign up'
45 }
46 },
47})
48β
49export const handleForm = createServerFn({
50 method: 'POST',
51})
52 .inputValidator((data: unknown) => {
53 if (!(data instanceof FormData)) {
54 throw new Error('Invalid form data')
55 }
56 return data
57 })
58 .handler(async (ctx) => {
59 try {
60 const validatedData = await serverValidate(ctx.data)
61 console.log('validatedData', validatedData)
62 // Persist the form data to the database
63 // await sql`
64 // INSERT INTO users (name, email, password)
65 // VALUES (${validatedData.name}, ${validatedData.email}, ${validatedData.password})
66 // `
67 } catch (e) {
68 if (e instanceof ServerValidateError) {
69 // Log form errors or do any other logic here
70 return e.response
71 }
72β
73 // Some other error occurred when parsing the form
74 console.error(e)
75 setResponseStatus(500)
76 return 'There was an internal error'
77 }
78β
79 return 'Form has validated successfully'
80 })
81```
82β
83Then we need to establish a way to grab the form data from `serverValidate`'s `response` using another server action:
84β
85```tsx app/routes/index.tsx
86import { getFormData } from '@tanstack/react-form-start'
87β
88export const getFormDataFromServer = createServerFn({ method: 'GET' }).handler(
89 async () => {
90 return getFormData()
91 },
92)
93```
94β
95Finally, we'll use `getFormDataFromServer` in our loader to get the state from our server into our client and `handleForm` in our client-side form component.
96β
97```tsx app/routes/index.tsx
98import { createFileRoute } from '@tanstack/react-router'
99import {
100 mergeForm,
101 useForm,
102 useStore,
103 useTransform,
104} from '@tanstack/react-form-start'
105β
106export const Route = createFileRoute('/')({
107 component: Home,
108 loader: async () => ({
109 state: await getFormDataFromServer(),
110 }),
111})
112β
113function Home() {
114 const { state } = Route.useLoaderData()
115 const form = useForm({
116 ...formOpts,
117 transform: useTransform((baseForm) => mergeForm(baseForm, state), [state]),
118 })
119β
120 const formErrors = useStore(form.store, (formState) => formState.errors)
121β
122 return (
123 <form action={handleForm.url} method="post" encType={'multipart/form-data'}>
124 {formErrors.map((error) => (
125 <p key={error as string}>{error}</p>
126 ))}
127β
128 <form.Field
129 name="age"
130 validators={{
131 onChange: ({ value }) =>
132 value < 8 ? 'Client validation: You must be at least 8' : undefined,
133 }}
134 >
135 {(field) => {
136 return (
137 <div>
138 <input
139 name={field.name}
140 type="number"
141 value={field.state.value}
142 onChange={(e) => field.handleChange(e.target.valueAsNumber)}
143 />
144 {field.state.meta.errors.map((error) => (
145 <p key={error as string}>{error}</p>
146 ))}
147 </div>
148 )
149 }}
150 </form.Field>
151 <form.Subscribe
152 selector={(formState) => [formState.canSubmit, formState.isSubmitting]}
153 >
154 {([canSubmit, isSubmitting]) => (
155 <button type="submit" disabled={!canSubmit}>
156 {isSubmitting ? '...' : 'Submit'}
157 </button>
158 )}
159 </form.Subscribe>
160 </form>
161 )
162}
163```
164β
165### useTransform
166β
167you may have noticed util function `useTransform` being used throughout these examples, it's primary responsibility is the merging of the server and client state. Under the hood it is a useCallback whose deps are that of the server state, when the server state changes it will automatically patch the client state.
168β
169```tsx
170const form = useForm({
171 ...formOpts,
172 transform: useTransform((baseForm) => mergeForm(baseForm, state), [state]),
173})
174```