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

index.ts

168 lines4.8 KB

1import { LitElement, html, nothing } from 'lit'
2import { customElement } from 'lit/decorators.js'
3import {
4 MutationObserver,
5 QueryClient,
6 QueryObserver,
7 keepPreviousData,
8} from '@tanstack/query-core'
9import { TanStackFormController, formOptions } from '@tanstack/lit-form'
10import { db, sleep } from './mock-db'
11import type { AnyFieldApi } from '@tanstack/lit-form'
12import type { QueryObserverResult } from '@tanstack/query-core'
13import type { StoredUser } from './mock-db'
14​
15const emptyUser: StoredUser = {
16 firstName: '',
17 lastName: '',
19​
20function fieldInfo(field: AnyFieldApi) {
21 return html`
22 ${
23 field.meta.isInvalid
24 ? html`<em role="alert">
25 ${field.errors.map((error) => error.message).join(', ')}
26 </em>`
27 : nothing
28 }
29 ${field.meta.isValidating ? 'Validating...' : nothing}
30 `
32​
33@customElement('tanstack-query-form')
34export class TanStackQueryForm extends LitElement {
35 private queryClient = new QueryClient()
36 private userQuery = new QueryObserver(this.queryClient, {
37 queryKey: ['data'],
38 queryFn: () => db.getData(),
39 placeholderData: keepPreviousData,
40 })
41 private userResult: QueryObserverResult<StoredUser> =
42 this.userQuery.getCurrentResult()
43 private unsubscribeQuery?: () => void
44 private currentDefaults = emptyUser
45​
46 private saveUser = new MutationObserver(this.queryClient, {
47 mutationFn: (value: StoredUser) => db.saveUser(value),
48 onSuccess: async () => {
49 await this.userQuery.refetch()
50 },
51 })
52​
53 private form = new TanStackFormController(this, this.formOptions(emptyUser))
54​
55 protected createRenderRoot() {
56 return this
57 }
58​
59 connectedCallback() {
60 super.connectedCallback()
61 this.unsubscribeQuery = this.userQuery.subscribe((result) => {
62 this.userResult = result
63 if (result.data && result.data !== this.currentDefaults) {
64 this.currentDefaults = result.data
65 this.form.update(this.formOptions(result.data))
66 }
67 this.requestUpdate()
68 })
69 }
70​
71 disconnectedCallback() {
72 this.unsubscribeQuery?.()
73 this.unsubscribeQuery = undefined
74 super.disconnectedCallback()
75 }
76​
77 private formOptions(defaultValues: StoredUser) {
78 return formOptions({
79 defaultValues,
80 onSubmit: async ({ formApi, value }) => {
81 await this.saveUser.mutate(value)
82 formApi.reset(value)
83 },
84 errorVisibility: ({ fieldState }) => fieldState.meta.isTouched,
85 })
86 }
87​
88 render() {
89 if (this.userResult.isPending) return html`<p>Loading...</p>`
90​
91 return html`
92 <h1>Query Integration Form Example</h1>
93 <form
94 @submit=${(event: SubmitEvent) => {
95 event.preventDefault()
96 event.stopPropagation()
97 void this.form.api.handleSubmit()
98 }}
99 >
100 ${this.form.field(
101 {
102 name: 'firstName',
103 validators: [
104 {
105 run: ({ value }) =>
106 !value
107 ? 'A first name is required'
108 : value.length < 3
109 ? 'First name must be at least 3 characters'
110 : undefined,
111 triggers: ['change'],
112 },
113 {
114 run: async ({ value }) => {
115 await sleep(1000)
116 return value.includes('error')
117 ? 'No "error" allowed in first name'
118 : undefined
119 },
120 triggers: ['change'],
121 triggerDebounceMs: 500,
122 },
123 ],
124 },
125 (field) => this.renderField(field, 'First Name'),
126 )}
127 ${this.form.field({ name: 'lastName' }, (field) =>
128 this.renderField(field, 'Last Name'),
129 )}
130 ${this.form.subscribe(
131 (state) => [state.canSubmit, state.isSubmitting] as const,
132 ([canSubmit, isSubmitting]) => html`
133 <button type="submit" ?disabled=${!canSubmit || isSubmitting}>
134 ${isSubmitting ? '...' : 'Submit'}
135 </button>
136 <button
137 type="reset"
138 @click=${(event: Event) => {
139 event.preventDefault()
140 this.form.api.reset()
141 }}
142 >
143 Reset
144 </button>
145 `,
146 )}
147 </form>
148 `
149 }
150​
151 private renderField(field: AnyFieldApi, label: string) {
152 return html`
153 <div>
154 <label for=${field.name}>${label}:</label>
155 <input
156 id=${field.name}
157 name=${field.name}
158 .value=${field.value}
159 @blur=${() => field.handleBlur()}
160 @input=${(event: InputEvent) =>
161 field.handleChange((event.currentTarget as HTMLInputElement).value)}
162 aria-invalid=${field.meta.isInvalid ? 'true' : 'false'}
163 />
164 ${fieldInfo(field)}
165 </div>
166 `
167 }