Open History to see the last commit
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
34}
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 }
57}
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 ${query.isError
423 ? html`<p data-testid="query-error">${String(query.error)}</p>`
424 : null}
425 ${this.resetError
426 ? html`<p data-testid="reset-error">${this.resetError}</p>`
427 : null}
428β
429 <section>
430 <label for="delayInput">Delay (ms)</label>
431 <input
432 id="delayInput"
433 data-testid="delay-input"
434 type="number"
435 min="0"
436 .value=${String(this.delayMs)}
437 @input=${this.onDelayInput}
438 />
439β
440 <label for="errorModeToggle">Force query error</label>
441 <input
442 id="errorModeToggle"
443 data-testid="force-error-toggle"
444 type="checkbox"
445 .checked=${this.forceErrorMode}
446 @change=${this.onErrorModeToggle}
447 />
448β
449 <button
450 data-testid="reset-demo-state"
451 @click=${() => this.resetDemoState()}
452 >
453 Reset Demo State
454 </button>
455 <button
456 data-testid="refetch"
457 @click=${() => this.projectsQuery.refetch()}
458 >
459 Refetch
460 </button>
461 <button
462 data-testid="prefetch-next"
463 @click=${() => this.prefetchNext()}
464 >
465 Prefetch Next
466 </button>
467 <button
468 data-testid="arm-mutation-error"
469 @click=${() => this.armNextMutationFailure()}
470 >
471 Fail Next Mutation
472 </button>
473 <div data-testid="mutation-control-status">
474 mutation-control: ${this.mutationControlStatus}
475 </div>
476 ${this.mutationControlError
477 ? html`<div data-testid="mutation-control-error">
478 ${this.mutationControlError}
479 </div>`
480 : null}
481 </section>
482β
483 <section>
484 <div data-testid="create-mutation-status">
485 create-mutation: ${createProject.status}
486 </div>
487 ${createProject.isError
488 ? html`<div data-testid="create-mutation-error">
489 ${String(createProject.error)}
490 </div>`
491 : null}
492β
493 <label for="projectNameInput">Project name</label>
494 <input
495 id="projectNameInput"
496 data-testid="project-name-input"
497 .value=${this.draftName}
498 @input=${this.onDraftNameInput}
499 />
500β
501 <label for="projectOwnerInput">Owner</label>
502 <input
503 id="projectOwnerInput"
504 data-testid="project-owner-input"
505 .value=${this.draftOwner}
506 @input=${this.onDraftOwnerInput}
507 />
508β
509 <button
510 data-testid="create-project"
511 ?disabled=${createProject.isPending}
512 @click=${() => this.submitCreateProject()}
513 >
514 Create Project
515 </button>
516 </section>
517β
518 <section>
519 <div data-testid="favorite-mutation-status">
520 favorite-mutation: ${favoriteProject.status}
521 </div>
522 ${favoriteProject.isError
523 ? html`<div data-testid="favorite-mutation-error">
524 ${String(favoriteProject.error)}
525 </div>`
526 : null}
527 </section>
528β
529 <section>
530 <button
531 data-testid="previous-page"
532 ?disabled=${this.page === 1 || query.isPlaceholderData}
533 @click=${() => this.goToPreviousPage()}
534 >
535 Previous
536 </button>
537 <button
538 data-testid="next-page"
539 ?disabled=${!hasMore || query.isPlaceholderData}
540 @click=${() => this.goToNextPage()}
541 >
542 Next
543 </button>
544 </section>
545β
546 <ul data-testid="project-list">
547 ${projects.map(
548 (project) => html`
549 <li data-testid="project-item">
550 <span data-testid="project-name"
551 >${project.id}: ${project.name} (${project.owner})</span
552 >
553 <span data-testid="project-favorite-state"
554 >${project.isFavorite ? 'favorite' : 'standard'}</span
555 >
556 <button
557 data-testid="toggle-favorite"
558 ?disabled=${favoriteProject.isPending}
559 @click=${() => this.toggleFavorite(project)}
560 >
561 ${project.isFavorite ? 'Unfavorite' : 'Favorite'}
562 </button>
563 </li>
564 `,
565 )}
566 </ul>
567 </main>
568 `
569 }
570}
571β
572customElements.define('pagination-demo', PaginationDemo)
573β
574class PaginationDemoRoot extends LitElement {
575 protected override createRenderRoot(): HTMLElement | DocumentFragment {
576 return this
577 }
578β
579 render() {
580 return html`
581 <pagination-query-provider>
582 <pagination-demo></pagination-demo>
583 </pagination-query-provider>
584 `
585 }
586}
587β
588customElements.define('pagination-demo-root', PaginationDemoRoot)