Open History to see the last commit
1import { useForm } from '@tanstack/preact-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/preact-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 )
16}
17β
18const emptyUser: StoredUser = {
19 firstName: '',
20 lastName: '',
21}
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 onInput={(e) => field.handleChange(e.currentTarget.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 onInput={(e) => field.handleChange(e.currentTarget.value)}
113 />
114 <FieldInfo field={field} />
115 </div>
116 )}
117 </form.Field>
118 <form.Subscribe
119 selector={(state) => [state.canSubmit, state.isSubmitting]}
120 children={([canSubmit, isSubmitting]) => (
121 <>
122 <button type="submit" disabled={!canSubmit}>
123 {isSubmitting ? '...' : 'Submit'}
124 </button>
125 <button type="reset" onClick={() => form.reset()}>
126 Reset
127 </button>
128 </>
129 )}
130 />
131 </form>
132 </div>
133 )
134}