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

app.component.ts

250 lines6.8 KB

1import {
2 ChangeDetectionStrategy,
3 Component,
4 inject,
5 signal,
6} from '@angular/core'
7import {
8 FormField,
9 applyEach,
10 debounce,
11 form,
12 minLength,
13 required,
14 submit as submitForm,
15 validateAsync,
16} from '@angular/forms/signals'
17import {
18 injectMutation,
19 injectQuery,
20 toResource,
21} from '@tanstack/angular-query'
22import { ValidationQueriesService } from './validation-queries.service'
23​
24@Component({
25 changeDetection: ChangeDetectionStrategy.OnPush,
26 selector: 'app-root',
27 imports: [FormField],
28 styleUrl: './app.component.css',
29 template: `
30 <main>
31 <h1>Username availability</h1>
32 <p>
33 Signal Forms uses a Resource backed by TanStack Query for async
34 validation. Try <code>taken</code> or any other username.
35 </p>
36​
37 <form (submit)="submit($event)">
38 <label>
39 Username
40 <input [formField]="registrationForm.username" />
41 </label>
42​
43 @if (registrationForm.username().pending()) {
44 <p class="checking">Checking availability...</p>
45 }
46​
47 @if (
48 registrationForm.username().touched() &&
49 registrationForm.username().invalid()
50 ) {
51 @for (error of registrationForm.username().errors(); track $index) {
52 <p class="error">{{ error.message }}</p>
53 }
54 }
55​
56 @if (
57 registrationForm.username().touched() &&
58 registrationForm.username().valid()
59 ) {
60 <p class="success">Username is available.</p>
61 }
62​
63 <p class="hint">
64 Invite-code validators are added with each array item. The query
65 resource does not exist until an invite code is added.
66 </p>
67​
68 <button type="button" (click)="addInviteCode()">Add invite code</button>
69​
70 @for (
71 inviteCode of registrationForm.inviteCodes;
72 track $index;
73 let index = $index
74 ) {
75 <div class="invite-code-row">
76 <label>
77 Invite code {{ index + 1 }}
78 <input [formField]="inviteCode" />
79 </label>
80​
81 <button type="button" (click)="removeInviteCode(index)">
82 Remove
83 </button>
84​
85 @if (inviteCode().pending()) {
86 <p class="checking">Checking invite code...</p>
87 }
88​
89 @if (inviteCode().touched() && inviteCode().invalid()) {
90 @for (error of inviteCode().errors(); track $index) {
91 <p class="error">{{ error.message }}</p>
92 }
93 }
94​
95 @if (inviteCode().touched() && inviteCode().valid()) {
96 <p class="success">Invite code is valid.</p>
97 }
98 </div>
99 }
100​
101 <button type="button" (click)="registrationForm().reloadValidation()">
102 Request validation again
103 </button>
104​
105 <button type="submit" [disabled]="registrationMutation.isPending()">
106 {{ registrationMutation.isPending() ? 'Saving...' : 'Submit' }}
107 </button>
108​
109 @if (registrationMutation.isError()) {
110 <p class="error">Could not submit the registration.</p>
111 }
112​
113 @if (
114 registrationMutation.isSuccess() && registrationMutation.data().ok
115 ) {
116 <p class="success">
117 Registration accepted for
118 <code>{{ registrationMutation.variables().username }}</code
119 >.
120 </p>
121 <p class="hint">
122 Mutation variables included
123 {{ registrationMutation.variables().inviteCodes.length }}
124 invite code(s).
125 </p>
126 }
127 </form>
128 </main>
129 `,
130})
131export class AppComponent {
132 private readonly queries = inject(ValidationQueriesService)
133 readonly model = signal({ username: '', inviteCodes: [] as Array<string> })
134 readonly registrationMutation = injectMutation(() =>
135 this.queries.submitRegistration(),
136 )
137​
138 readonly registrationForm = form(this.model, (path) => {
139 debounce(path.username, 300)
140 required(path.username, { message: 'Username is required' })
141 minLength(path.username, 3, {
142 message: 'Username must be at least 3 characters',
143 })
144​
145 validateAsync(path.username, {
146 params: ({ value }) => value().trim() || undefined,
147 factory: (username) => {
148 const query = injectQuery(() => {
149 const name = username() ?? ''
150 return {
151 ...this.queries.usernameAvailability(name),
152 enabled: !!name,
153 }
154 })
155​
156 return toResource(query)
157 },
158 onSuccess: (result) =>
159 result.available
160 ? null
161 : {
162 kind: 'usernameTaken',
163 message: 'Username is already taken',
164 },
165 onError: () => ({
166 kind: 'usernameUnavailable',
167 message: 'Could not check username availability',
168 }),
169 })
170​
171 applyEach(path.inviteCodes, (inviteCode) => {
172 debounce(inviteCode, 300)
173 required(inviteCode, { message: 'Invite code is required' })
174 minLength(inviteCode, 3, {
175 message: 'Invite code must be at least 3 characters',
176 })
177​
178 validateAsync(inviteCode, {
179 params: ({ value }) => value().trim() || undefined,
180 factory: (code) => {
181 const query = injectQuery(() => {
182 const value = code() ?? ''
183 return {
184 ...this.queries.inviteCodeValidation(value),
185 enabled: !!value,
186 }
187 })
188​
189 return toResource(query)
190 },
191 onSuccess: (result) =>
192 result.valid
193 ? null
194 : {
195 kind: 'invalidInviteCode',
196 message: 'Invite code must start with TEAM-',
197 },
198 onError: () => ({
199 kind: 'inviteCodeUnavailable',
200 message: 'Could not check the invite code',
201 }),
202 })
203 })
204 })
205​
206 addInviteCode() {
207 this.model.update((model) => ({
208 ...model,
209 inviteCodes: [...model.inviteCodes, ''],
210 }))
211 }
212​
213 removeInviteCode(index: number) {
214 this.model.update((model) => ({
215 ...model,
216 inviteCodes: model.inviteCodes.filter(
217 (_, itemIndex) => itemIndex !== index,
218 ),
219 }))
220 }
221​
222 async submit(event: SubmitEvent) {
223 event.preventDefault()
224​
225 const success = await submitForm(this.registrationForm, {
226 ignoreValidators: 'none',
227 action: async (field) => {
228 const result = await this.registrationMutation.mutateAsync(
229 field().value(),
230 )
231​
232 if (!result.ok) {
233 return result.errors.map((error) => ({
234 fieldTree:
235 error.fieldPath[0] === 'username'
236 ? this.registrationForm.username
237 : this.registrationForm.inviteCodes[error.fieldPath[1]],
238 kind: 'server',
239 message: error.error,
240 }))
241 }
242​
243 return undefined
244 },
245 })
246 if (success) {
247 this.model.set({ username: '', inviteCodes: [] })
248 }
249 }