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