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