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

main.ts

598 lines16.3 KB

1import { LitElement, html } from 'lit'
2import {
3 QueryClient,
4 QueryClientProvider,
5 createMutationController,
6 createQueryController,
7 keepPreviousData,
8 noop,
9} from '@tanstack/lit-query'
10import {
11 armNextProjectMutationFailureOnServer,
12 createProjectOnServer,
13 fetchProjectsPage,
14 projectsQueryKey,
15 resetProjectsApiState,
16 toggleProjectFavoriteOnServer,
17} from './api'
18import type {
19 CreateQueryOptions,
20 MutationResultAccessor,
21 QueryKey,
22 QueryResultAccessor,
23} from '@tanstack/lit-query'
24import type {
25 CreateProjectInput,
26 Project,
27 ProjectsPageResponse,
28 ToggleProjectFavoriteInput,
29} from './api'
30​
31type ProjectsCacheSnapshot = Array<[QueryKey, ProjectsPageResponse | undefined]>
32type FavoriteMutationContext = {
33 snapshots: ProjectsCacheSnapshot
35​
36const queryClient = new QueryClient({
37 defaultOptions: {
38 queries: {
39 retry: false,
40 staleTime: 5_000,
41 },
42 mutations: {
43 retry: false,
44 },
45 },
46})
47​
48class PaginationQueryProvider extends QueryClientProvider {
49 constructor() {
50 super()
51 this.client = queryClient
52 }
53​
54 protected override createRenderRoot(): HTMLElement | DocumentFragment {
55 return this
56 }
58​
59customElements.define('pagination-query-provider', PaginationQueryProvider)
60​
61class PaginationDemo extends LitElement {
62 static properties = {
63 page: { state: true },
64 delayMs: { state: true },
65 forceErrorMode: { state: true },
66 prefetchStatus: { state: true },
67 resetError: { state: true },
68 draftName: { state: true },
69 draftOwner: { state: true },
70 mutationControlStatus: { state: true },
71 mutationControlError: { state: true },
72 }
73​
74 private page = 1
75 private delayMs = 250
76 private forceErrorMode = false
77 private prefetchStatus = 'idle'
78 private resetError: string | undefined
79 private draftName = 'Platform Rollout'
80 private draftOwner = 'Team 6'
81 private mutationControlStatus = 'idle'
82 private mutationControlError: string | undefined
83 private lastAutoPrefetchPage = 0
84 private readonly projectsQueryOptions: CreateQueryOptions<
85 ProjectsPageResponse,
86 Error
87 >
88 private readonly projectsQuery: QueryResultAccessor<
89 ProjectsPageResponse,
90 Error
91 >
92 private readonly createProjectMutation: MutationResultAccessor<
93 Project,
94 Error,
95 CreateProjectInput,
96 unknown
97 >
98 private readonly favoriteMutation: MutationResultAccessor<
99 Project,
100 Error,
101 ToggleProjectFavoriteInput,
102 FavoriteMutationContext
103 >
104​
105 constructor() {
106 super()
107​
108 this.projectsQueryOptions = {
109 queryKey: projectsQueryKey(this.page, this.delayMs, this.forceErrorMode),
110 queryFn: () =>
111 fetchProjectsPage(this.page, this.delayMs, this.forceErrorMode),
112 placeholderData: keepPreviousData,
113 }
114​
115 this.projectsQuery = createQueryController<ProjectsPageResponse, Error>(
116 this,
117 this.projectsQueryOptions,
118 )
119​
120 this.createProjectMutation = createMutationController<
121 Project,
122 Error,
123 CreateProjectInput
124 >(
125 this,
126 {
127 mutationKey: ['create-project'],
128 mutationFn: async (input) => {
129 const response = await createProjectOnServer(input)
130 return response.project
131 },
132 onMutate: () => {
133 this.mutationControlStatus = 'idle'
134 this.mutationControlError = undefined
135 },
136 onSuccess: async () => {
137 this.page = 1
138 this.lastAutoPrefetchPage = 0
139 this.prefetchStatus = 'idle'
140 this.draftName = ''
141 this.draftOwner = 'Team 6'
142 this.syncProjectsQueryOptions()
143 await queryClient.invalidateQueries({
144 queryKey: ['projects'],
145 refetchType: 'none',
146 })
147 await this.projectsQuery.refetch()
148 },
149 },
150 queryClient,
151 )
152​
153 this.favoriteMutation = createMutationController<
154 Project,
155 Error,
156 ToggleProjectFavoriteInput,
157 FavoriteMutationContext
158 >(
159 this,
160 {
161 mutationKey: ['toggle-project-favorite'],
162 mutationFn: async (input) => {
163 const response = await toggleProjectFavoriteOnServer(input)
164 return response.project
165 },
166 onMutate: async (variables) => {
167 this.mutationControlStatus = 'idle'
168 this.mutationControlError = undefined
169 await queryClient.cancelQueries({ queryKey: ['projects'] })
170​
171 const snapshots = queryClient.getQueriesData<ProjectsPageResponse>({
172 queryKey: ['projects'],
173 })
174​
175 for (const [key, existing] of snapshots) {
176 if (!existing) {
177 continue
178 }
179​
180 queryClient.setQueryData<ProjectsPageResponse>(key, {
181 ...existing,
182 projects: existing.projects.map((project) =>
183 project.id === variables.id
184 ? { ...project, isFavorite: variables.isFavorite }
185 : project,
186 ),
187 })
188 }
189​
190 return { snapshots }
191 },
192 onError: (_error, _variables, context) => {
193 for (const [key, snapshot] of context?.snapshots ?? []) {
194 queryClient.setQueryData(key, snapshot)
195 }
196 },
197 onSettled: async () => {
198 await queryClient.invalidateQueries({ queryKey: ['projects'] })
199 },
200 },
201 queryClient,
202 )
203 }
204​
205 protected override createRenderRoot(): HTMLElement | DocumentFragment {
206 return this
207 }
208​
209 override updated(): void {
210 this.maybePrefetchNextPage()
211 }
212​
213 private syncProjectsQueryOptions(): void {
214 this.projectsQueryOptions.queryKey = projectsQueryKey(
215 this.page,
216 this.delayMs,
217 this.forceErrorMode,
218 )
219 this.projectsQueryOptions.queryFn = () =>
220 fetchProjectsPage(this.page, this.delayMs, this.forceErrorMode)
221 }
222​
223 private refetchForCurrentState(): void {
224 this.syncProjectsQueryOptions()
225 void this.projectsQuery.refetch()
226 }
227​
228 private async maybePrefetchNextPage(): Promise<void> {
229 const query = this.projectsQuery()
230 const currentData = query.data
231​
232 if (!currentData || query.isPlaceholderData || !currentData.hasMore) {
233 return
234 }
235​
236 if (this.lastAutoPrefetchPage === currentData.page) {
237 return
238 }
239​
240 this.lastAutoPrefetchPage = currentData.page
241 await this.prefetchPage(currentData.page + 1)
242 }
243​
244 private onDelayInput(event: Event): void {
245 const target = event.target as HTMLInputElement
246 const nextValue = Number.parseInt(target.value, 10)
247​
248 if (!Number.isInteger(nextValue) || nextValue < 0) {
249 return
250 }
251​
252 this.delayMs = nextValue
253 this.refetchForCurrentState()
254 }
255​
256 private onErrorModeToggle(event: Event): void {
257 const target = event.target as HTMLInputElement
258 this.forceErrorMode = target.checked
259 this.refetchForCurrentState()
260 }
261​
262 private onDraftNameInput(event: Event): void {
263 const target = event.target as HTMLInputElement
264 this.draftName = target.value
265 }
266​
267 private onDraftOwnerInput(event: Event): void {
268 const target = event.target as HTMLInputElement
269 this.draftOwner = target.value
270 }
271​
272 private async prefetchPage(targetPage: number): Promise<void> {
273 this.prefetchStatus = `pending:${targetPage}`
274​
275 try {
276 await queryClient
277 .query({
278 queryKey: projectsQueryKey(
279 targetPage,
280 this.delayMs,
281 this.forceErrorMode,
282 ),
283 queryFn: () =>
284 fetchProjectsPage(targetPage, this.delayMs, this.forceErrorMode),
285 })
286 .catch(noop)
287 this.prefetchStatus = `ready:${targetPage}`
288 } catch (error) {
289 this.prefetchStatus = `error:${String(error)}`
290 }
291 }
292​
293 private async prefetchNext(): Promise<void> {
294 const query = this.projectsQuery()
295 const currentData = query.data
296​
297 if (!currentData?.hasMore) {
298 this.prefetchStatus = 'skipped:no-next-page'
299 return
300 }
301​
302 await this.prefetchPage(currentData.page + 1)
303 }
304​
305 private goToPreviousPage(): void {
306 if (this.page > 1) {
307 this.page -= 1
308 this.refetchForCurrentState()
309 }
310 }
311​
312 private goToNextPage(): void {
313 const currentData = this.projectsQuery().data
314 if (!currentData?.hasMore) {
315 return
316 }
317​
318 this.page += 1
319 this.refetchForCurrentState()
320 }
321​
322 private async resetDemoState(): Promise<void> {
323 this.resetError = undefined
324​
325 try {
326 await resetProjectsApiState()
327 this.page = 1
328 this.delayMs = 250
329 this.forceErrorMode = false
330 this.prefetchStatus = 'idle'
331 this.resetError = undefined
332 this.draftName = 'Platform Rollout'
333 this.draftOwner = 'Team 6'
334 this.mutationControlStatus = 'idle'
335 this.mutationControlError = undefined
336 this.lastAutoPrefetchPage = 0
337 this.syncProjectsQueryOptions()
338 this.createProjectMutation.reset()
339 this.favoriteMutation.reset()
340 await queryClient.resetQueries({ queryKey: ['projects'] })
341 await this.projectsQuery.refetch()
342 } catch (error) {
343 this.resetError = String(error)
344 }
345 }
346​
347 private submitCreateProject(): void {
348 const name = this.draftName.trim()
349 const owner = this.draftOwner.trim()
350​
351 if (!name || !owner) {
352 return
353 }
354​
355 this.createProjectMutation.mutate({ name, owner })
356 }
357​
358 private toggleFavorite(project: Project): void {
359 this.favoriteMutation.mutate({
360 id: project.id,
361 isFavorite: !project.isFavorite,
362 })
363 }
364​
365 private async armNextMutationFailure(): Promise<void> {
366 this.mutationControlError = undefined
367​
368 try {
369 await armNextProjectMutationFailureOnServer()
370 this.mutationControlStatus = 'armed'
371 } catch (error) {
372 this.mutationControlStatus = 'error'
373 this.mutationControlError = String(error)
374 }
375 }
376​
377 render() {
378 const query = this.projectsQuery()
379 const projects = query.data?.projects ?? []
380 const hasMore = query.data?.hasMore ?? false
381 const createProject = this.createProjectMutation()
382 const favoriteProject = this.favoriteMutation()
383​
384 return html`
385 <main>
386 <h1>TanStack Lit Query Pagination Demo</h1>
387 <p>
388 Pagination + mutation demo with optimistic favorite toggles,
389 invalidation, and deterministic server failures.
390 </p>
391​
392 <section>
393 <div data-testid="query-status">query: ${query.status}</div>
394 <div data-testid="is-fetching">
395 isFetching: ${query.isFetching ? 'yes' : 'no'}
396 </div>
397 <div data-testid="is-placeholder">
398 isPlaceholderData: ${query.isPlaceholderData ? 'yes' : 'no'}
399 </div>
400 <div data-testid="current-page">page: ${this.page}</div>
401 <div data-testid="response-page">
402 response-page: ${query.data?.page ?? '-'}
403 </div>
404 <div data-testid="has-more">has-more: ${hasMore ? 'yes' : 'no'}</div>
405 <div data-testid="total-projects">
406 total-projects: ${query.data?.totalProjects ?? 0}
407 </div>
408 <div data-testid="total-request-count">
409 total-requests: ${query.data?.requestMeta.totalRequestCount ?? 0}
410 </div>
411 <div data-testid="page-request-count">
412 page-requests: ${query.data?.requestMeta.pageRequestCount ?? 0}
413 </div>
414 <div data-testid="total-mutation-count">
415 total-mutations: ${query.data?.requestMeta.totalMutationCount ?? 0}
416 </div>
417 <div data-testid="prefetch-status">
418 prefetch: ${this.prefetchStatus}
419 </div>
420 </section>
421​
422 ${
423 query.isError
424 ? html`<p data-testid="query-error">${String(query.error)}</p>`
425 : null
426 }
427 ${
428 this.resetError
429 ? html`<p data-testid="reset-error">${this.resetError}</p>`
430 : null
431 }
432​
433 <section>
434 <label for="delayInput">Delay (ms)</label>
435 <input
436 id="delayInput"
437 data-testid="delay-input"
438 type="number"
439 min="0"
440 .value=${String(this.delayMs)}
441 @input=${this.onDelayInput}
442 />
443​
444 <label for="errorModeToggle">Force query error</label>
445 <input
446 id="errorModeToggle"
447 data-testid="force-error-toggle"
448 type="checkbox"
449 .checked=${this.forceErrorMode}
450 @change=${this.onErrorModeToggle}
451 />
452​
453 <button
454 data-testid="reset-demo-state"
455 @click=${() => this.resetDemoState()}
456 >
457 Reset Demo State
458 </button>
459 <button
460 data-testid="refetch"
461 @click=${() => this.projectsQuery.refetch()}
462 >
463 Refetch
464 </button>
465 <button
466 data-testid="prefetch-next"
467 @click=${() => this.prefetchNext()}
468 >
469 Prefetch Next
470 </button>
471 <button
472 data-testid="arm-mutation-error"
473 @click=${() => this.armNextMutationFailure()}
474 >
475 Fail Next Mutation
476 </button>
477 <div data-testid="mutation-control-status">
478 mutation-control: ${this.mutationControlStatus}
479 </div>
480 ${
481 this.mutationControlError
482 ? html`<div data-testid="mutation-control-error">
483 ${this.mutationControlError}
484 </div>`
485 : null
486 }
487 </section>
488​
489 <section>
490 <div data-testid="create-mutation-status">
491 create-mutation: ${createProject.status}
492 </div>
493 ${
494 createProject.isError
495 ? html`<div data-testid="create-mutation-error">
496 ${String(createProject.error)}
497 </div>`
498 : null
499 }
500​
501 <label for="projectNameInput">Project name</label>
502 <input
503 id="projectNameInput"
504 data-testid="project-name-input"
505 .value=${this.draftName}
506 @input=${this.onDraftNameInput}
507 />
508​
509 <label for="projectOwnerInput">Owner</label>
510 <input
511 id="projectOwnerInput"
512 data-testid="project-owner-input"
513 .value=${this.draftOwner}
514 @input=${this.onDraftOwnerInput}
515 />
516​
517 <button
518 data-testid="create-project"
519 ?disabled=${createProject.isPending}
520 @click=${() => this.submitCreateProject()}
521 >
522 Create Project
523 </button>
524 </section>
525​
526 <section>
527 <div data-testid="favorite-mutation-status">
528 favorite-mutation: ${favoriteProject.status}
529 </div>
530 ${
531 favoriteProject.isError
532 ? html`<div data-testid="favorite-mutation-error">
533 ${String(favoriteProject.error)}
534 </div>`
535 : null
536 }
537 </section>
538​
539 <section>
540 <button
541 data-testid="previous-page"
542 ?disabled=${this.page === 1 || query.isPlaceholderData}
543 @click=${() => this.goToPreviousPage()}
544 >
545 Previous
546 </button>
547 <button
548 data-testid="next-page"
549 ?disabled=${!hasMore || query.isPlaceholderData}
550 @click=${() => this.goToNextPage()}
551 >
552 Next
553 </button>
554 </section>
555​
556 <ul data-testid="project-list">
557 ${projects.map(
558 (project) => html`
559 <li data-testid="project-item">
560 <span data-testid="project-name"
561 >${project.id}: ${project.name} (${project.owner})</span
562 >
563 <span data-testid="project-favorite-state"
564 >${project.isFavorite ? 'favorite' : 'standard'}</span
565 >
566 <button
567 data-testid="toggle-favorite"
568 ?disabled=${favoriteProject.isPending}
569 @click=${() => this.toggleFavorite(project)}
570 >
571 ${project.isFavorite ? 'Unfavorite' : 'Favorite'}
572 </button>
573 </li>
574 `,
575 )}
576 </ul>
577 </main>
578 `
579 }
581​
582customElements.define('pagination-demo', PaginationDemo)
583​
584class PaginationDemoRoot extends LitElement {
585 protected override createRenderRoot(): HTMLElement | DocumentFragment {
586 return this
587 }
588​
589 render() {
590 return html`
591 <pagination-query-provider>
592 <pagination-demo></pagination-demo>
593 </pagination-query-provider>
594 `
595 }
597​
598customElements.define('pagination-demo-root', PaginationDemoRoot)