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