Open History to see the last commit
1import { LitElement, html } from 'lit'
2import { ref } from 'lit/directives/ref.js'
3import { createInfiniteQueryController } from '@tanstack/lit-query'
4import { projectsQueries } from './services/projects/queries'
5β
6class ExampleView extends LitElement {
7 static properties = {
8 inView: { state: true },
9 }
10β
11 private inView = false
12 private observer: IntersectionObserver | undefined
13β
14 private readonly projects = createInfiniteQueryController(
15 this,
16 projectsQueries.infinite(),
17 )
18β
19 protected override createRenderRoot(): HTMLElement | DocumentFragment {
20 return this
21 }
22β
23 override disconnectedCallback() {
24 super.disconnectedCallback()
25 this.observer?.disconnect()
26 }
27β
28 protected override updated() {
29 const { hasNextPage, isFetchingNextPage } = this.projects()
30β
31 if (this.inView && hasNextPage && !isFetchingNextPage) {
32 this.projects.fetchNextPage()
33 }
34 }
35β
36 private observeLoadMoreButton = (element?: Element) => {
37 this.observer?.disconnect()
38β
39 if (!element) return
40β
41 this.observer = new IntersectionObserver(([entry]) => {
42 this.inView = entry.isIntersecting
43 })
44 this.observer.observe(element)
45 }
46β
47 private renderProjects() {
48 const {
49 status,
50 data,
51 error,
52 isFetching,
53 isFetchingNextPage,
54 isFetchingPreviousPage,
55 hasNextPage,
56 hasPreviousPage,
57 } = this.projects()
58β
59 if (status === 'pending') return html`<p>Loading...</p>`
60 if (status === 'error') return html`<span>Error: ${error.message}</span>`
61β
62 return html`
63 <div>
64 <button
65 type="button"
66 @click=${() => this.projects.fetchPreviousPage()}
67 ?disabled=${!hasPreviousPage || isFetchingPreviousPage}
68 >
69 ${
70 isFetchingPreviousPage
71 ? 'Loading more...'
72 : hasPreviousPage
73 ? 'Load Older'
74 : 'Nothing more to load'
75 }
76 </button>
77 </div>
78 ${data.pages.map((page) =>
79 page.data.map(
80 (project) => html`
81 <p
82 style="border: 1px solid gray; border-radius: 5px; padding: 10rem 1rem; background: hsla(${
83 project.id * 30
84 }, 60%, 80%, 1)"
85 >
86 ${project.name}
87 </p>
88 `,
89 ),
90 )}
91 <div>
92 <button
93 type="button"
94 ${ref(this.observeLoadMoreButton)}
95 @click=${() => this.projects.fetchNextPage()}
96 ?disabled=${!hasNextPage || isFetchingNextPage}
97 >
98 ${
99 isFetchingNextPage
100 ? 'Loading more...'
101 : hasNextPage
102 ? 'Load Newer'
103 : 'Nothing more to load'
104 }
105 </button>
106 </div>
107 <div>
108 ${isFetching && !isFetchingNextPage ? 'Background Updating...' : null}
109 </div>
110 `
111 }
112β
113 render() {
114 return html`
115 <div>
116 <h1>Infinite Loading</h1>
117 ${this.renderProjects()}
118 <hr />
119 <a href="/about">Go to another page</a>
120 </div>
121 `
122 }
123}
124β
125customElements.define('example-view', ExampleView)