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

remix.md

158 lines4.5 KB

1---
2id: remix
3title: TanStack Form - Remix
4---
5​
6## Using TanStack Form in Remix
7​
8> Before reading this section, it's suggested you understand how Remix actions work. [Check out Remix's docs for more information](https://remix.run/docs/en/main/discussion/data-flow#route-action)
9​
10### Remix Prerequisites
11​
12- Start a new `Remix` project, following the steps in the [Remix Documentation](https://remix.run/docs/en/main/start/quickstart).
13- Install `@tanstack/react-form-start`
14- Install any [form validator](./validation#validation-through-schema-libraries) of your choice. [Optional]
15​
16## Remix 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 routes/_index/route.tsx
21import { formOptions } from '@tanstack/react-form-remix'
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 [an action](https://remix.run/docs/en/main/discussion/data-flow#route-action) that will handle the form submission on the server.
33​
34```tsx routes/_index/route.tsx
35import {
36 ServerValidateError,
37 createServerValidate,
38 formOptions,
39} from '@tanstack/react-form-remix'
40​
41import type { ActionFunctionArgs } from '@remix-run/node'
42​
43// Create the server action that will infer the types of the form from `formOpts`
44const serverValidate = createServerValidate({
45 ...formOpts,
46 onServerValidate: ({ value }) => {
47 if (value.age < 12) {
48 return 'Server validation: You must be at least 12 to sign up'
49 }
50 },
51})
52​
53export async function action({ request }: ActionFunctionArgs) {
54 const formData = await request.formData()
55 try {
56 const validatedData = await serverValidate(formData)
57 console.log('validatedData', validatedData)
58 // Persist the form data to the database
59 // await sql`
60 // INSERT INTO users (name, email, password)
61 // VALUES (${validatedData.name}, ${validatedData.email}, ${validatedData.password})
62 // `
63 } catch (e) {
64 if (e instanceof ServerValidateError) {
65 return e.formState
66 }
67​
68 // Some other error occurred while validating your form
69 throw e
70 }
71​
72 // Your form has successfully validated!
74```
75​
76Finally, the `action` will be called when the form submits.
77​
78```tsx
79// routes/_index/route.tsx
80import { Form, useActionData } from '@remix-run/react'
81import { mergeForm, useForm, useStore } from '@tanstack/react-form'
82import {
83 ServerValidateError,
84 createServerValidate,
85 formOptions,
86 initialFormState,
87 useTransform,
88} from '@tanstack/react-form-remix'
89​
90export default function Index() {
91 const actionData = useActionData<typeof action>()
92​
93 const form = useForm({
94 ...formOpts,
95 transform: useTransform(
96 (baseForm) => mergeForm(baseForm, actionData ?? initialFormState),
97 [actionData],
98 ),
99 })
100​
101 const formErrors = useStore(form.store, (formState) => formState.errors)
102​
103 return (
104 <form method="post" onSubmit={() => form.handleSubmit()}>
105 {formErrors.map((error) => (
106 <p key={error as string}>{error}</p>
107 ))}
108​
109 <form.Field
110 name="age"
111 validators={{
112 onChange: ({ value }) =>
113 value < 8 ? 'Client validation: You must be at least 8' : undefined,
114 }}
115 >
116 {(field) => {
117 return (
118 <div>
119 <input
120 name="age"
121 type="number"
122 value={field.state.value}
123 onChange={(e) => field.handleChange(e.target.valueAsNumber)}
124 />
125 {field.state.meta.errors.map((error) => (
126 <p key={error as string}>{error}</p>
127 ))}
128 </div>
129 )
130 }}
131 </form.Field>
132 <form.Subscribe
133 selector={(formState) => [formState.canSubmit, formState.isSubmitting]}
134 >
135 {([canSubmit, isSubmitting]) => (
136 <button type="submit" disabled={!canSubmit}>
137 {isSubmitting ? '...' : 'Submit'}
138 </button>
139 )}
140 </form.Subscribe>
141 </form>
142 )
144```
145​
146### useTransform
147​
148you may have noticed util function `useTransform` being used throughout these examples, its 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.
149​
150```tsx
151const form = useForm({
152 ...formOpts,
153 transform: useTransform(
154 (baseForm) => mergeForm(baseForm, actionData ?? initialFormState),
155 [actionData],
156 ),
157})
158```