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

app.tsx

135 lines3.8 KB

1import { useForm } from '@tanstack/react-form'
2import { keepPreviousData, useMutation, useQuery } from '@tanstack/react-query'
3import { db, sleep } from './mock-db'
4import type { StoredUser } from './mock-db'
5import type { AnyFieldApi } from '@tanstack/react-form'
6​
7function FieldInfo({ field }: { field: AnyFieldApi }) {
8 return (
9 <>
10 {field.meta.isInvalid && (
11 <em>{field.errors.map((error) => error.message).join(',')}</em>
12 )}
13 {field.meta.isValidating ? 'Validating...' : null}
14 </>
15 )
17​
18const emptyUser: StoredUser = {
19 firstName: '',
20 lastName: '',
22​
23export function App() {
24 const userQuery = useQuery({
25 queryKey: ['data'],
26 queryFn: () => db.getData(),
27 // Keeps the old values present while refetching new ones
28 placeholderData: keepPreviousData,
29 })
30​
31 const saveUserMutation = useMutation({
32 mutationFn: async (value: StoredUser) => {
33 return db.saveUser(value)
34 },
35 onSuccess: async () => {
36 // Invalidating query to recheck fresh data
37 await userQuery.refetch()
38 },
39 })
40​
41 const form = useForm({
42 defaultValues: userQuery.data ?? emptyUser,
43 onSubmit: async ({ formApi, value }) => {
44 await saveUserMutation.mutateAsync(value)
45​
46 // Pass optimistic values to the form so that it doesn't show old values
47 formApi.reset(value)
48 },
49 // Only show errors if the field has been touched
50 errorVisibility: ({ fieldState }) => fieldState.meta.isTouched,
51 })
52​
53 if (userQuery.isLoading) return <p>Loading..</p>
54​
55 return (
56 <div>
57 <h1>Simple Form Example</h1>
58 <form
59 onSubmit={(e) => {
60 e.preventDefault()
61 e.stopPropagation()
62 form.handleSubmit()
63 }}
64 >
65 <form.Field
66 name="firstName"
67 validators={[
68 {
69 run: ({ value }) =>
70 !value
71 ? 'A first name is required'
72 : value.length < 3
73 ? 'First name must be at least 3 characters'
74 : undefined,
75 triggers: ['change'],
76 },
77 {
78 run: async ({ value }) => {
79 await sleep(1000)
80 return (
81 value.includes('error') && 'No "error" allowed in first name'
82 )
83 },
84 triggers: ['change'],
85 triggerDebounceMs: 500,
86 },
87 ]}
88 >
89 {(field) => (
90 <div>
91 <label htmlFor={field.name}>First Name:</label>
92 <input
93 id={field.name}
94 name={field.name}
95 value={field.value}
96 onBlur={field.handleBlur}
97 onChange={(e) => field.handleChange(e.target.value)}
98 />
99 <FieldInfo field={field} />
100 </div>
101 )}
102 </form.Field>
103 <form.Field name="lastName">
104 {(field) => (
105 <div>
106 <label htmlFor={field.name}>Last Name:</label>
107 <input
108 id={field.name}
109 name={field.name}
110 value={field.value}
111 onBlur={field.handleBlur}
112 onChange={(e) => field.handleChange(e.target.value)}
113 />
114 <FieldInfo field={field} />
115 </div>
116 )}
117 </form.Field>
118 <form.Subscribe
119 selector={(state) => [state.canSubmit, state.isSubmitting]}
120 >
121 {([canSubmit, isSubmitting]) => (
122 <>
123 <button type="submit" disabled={!canSubmit}>
124 {isSubmitting ? '...' : 'Submit'}
125 </button>
126 <button type="reset" onClick={() => form.reset()}>
127 Reset
128 </button>
129 </>
130 )}
131 </form.Subscribe>
132 </form>
133 </div>
134 )