Open History to see the last commit
1import { LitElement, html } from 'lit'
2import {
3 QueryClient,
4 QueryClientProvider,
5 createMutationController,
6 createQueryController,
7 useIsFetching,
8 useIsMutating,
9} from '@tanstack/lit-query'
10import {
11 addTodoOnServer,
12 failNextFetchRequest,
13 failNextMutationRequest,
14 fetchTodosFromServer,
15 resetTodoApi,
16} from './todoApi'
17import type { Todo, TodosResponse } from './todoApi'
18β
19resetTodoApi()
20β
21const demoQueryClient = new QueryClient({
22 defaultOptions: {
23 queries: {
24 retry: false,
25 },
26 mutations: {
27 retry: false,
28 },
29 },
30})
31β
32class DemoQueryProvider extends QueryClientProvider {
33 constructor() {
34 super()
35 this.client = demoQueryClient
36 }
37β
38 protected override createRenderRoot(): HTMLElement | DocumentFragment {
39 return this
40 }
41}
42β
43customElements.define('demo-query-provider', DemoQueryProvider)
44β
45class TanstackLitQueryDemo extends LitElement {
46 static properties = {
47 nextTodoTitle: { state: true },
48 cacheSeedCount: { state: true },
49 }
50β
51 private nextTodoTitle = 'Add mutation assertion'
52 private cacheSeedCount = 0
53β
54 private readonly todosQuery = createQueryController<TodosResponse, Error>(
55 this,
56 {
57 queryKey: ['todos'],
58 queryFn: fetchTodosFromServer,
59 },
60 )
61β
62 private readonly createTodoMutation = createMutationController<
63 Todo,
64 Error,
65 string
66 >(this, {
67 mutationKey: ['create-todo'],
68 mutationFn: addTodoOnServer,
69 onSuccess: (createdTodo) => {
70 demoQueryClient.setQueryData<TodosResponse>(['todos'], (existing) => {
71 if (!existing) {
72 return {
73 items: [createdTodo],
74 requestCount: 0,
75 source: 'cache',
76 }
77 }
78β
79 return {
80 items: [...existing.items, createdTodo],
81 requestCount: existing.requestCount,
82 source: 'cache',
83 }
84 })
85 },
86 })
87β
88 private readonly isFetching = useIsFetching(this, {
89 queryKey: ['todos'],
90 })
91β
92 private readonly isMutating = useIsMutating(this, {
93 mutationKey: ['create-todo'],
94 })
95β
96 protected override createRenderRoot(): HTMLElement | DocumentFragment {
97 return this
98 }
99β
100 private onTitleInput(event: Event): void {
101 const target = event.target as HTMLInputElement
102 this.nextTodoTitle = target.value
103 }
104β
105 private addTodo(): void {
106 const title = this.nextTodoTitle.trim()
107 if (!title) {
108 return
109 }
110β
111 this.createTodoMutation.mutate(title)
112 this.nextTodoTitle = ''
113 }
114β
115 private async invalidateTodos(): Promise<void> {
116 await demoQueryClient.invalidateQueries({ queryKey: ['todos'] })
117 }
118β
119 private seedCacheOnlyTodo(): void {
120 this.cacheSeedCount += 1
121β
122 const seedTodo: Todo = {
123 id: 10000 + this.cacheSeedCount,
124 title: `Seeded cache todo ${this.cacheSeedCount}`,
125 }
126β
127 demoQueryClient.setQueryData<TodosResponse>(['todos'], (existing) => {
128 if (!existing) {
129 return {
130 items: [seedTodo],
131 requestCount: 0,
132 source: 'cache',
133 }
134 }
135β
136 return {
137 items: [...existing.items, seedTodo],
138 requestCount: existing.requestCount,
139 source: 'cache',
140 }
141 })
142 }
143β
144 private forceNextFetchFailure(): void {
145 failNextFetchRequest()
146 }
147β
148 private forceNextMutationFailure(): void {
149 failNextMutationRequest()
150 }
151β
152 private async resetDemoState(): Promise<void> {
153 resetTodoApi()
154 this.cacheSeedCount = 0
155 this.nextTodoTitle = 'Add mutation assertion'
156β
157 await demoQueryClient.resetQueries({ queryKey: ['todos'] })
158 this.createTodoMutation.reset()
159 }
160β
161 render() {
162 const query = this.todosQuery()
163 const mutation = this.createTodoMutation()
164 const todos = query.data?.items ?? []
165β
166 return html`
167 <main>
168 <h1>TanStack Lit Query E2E Demo</h1>
169 <p>Verifies integration between Lit, query-core, and this adapter.</p>
170β
171 <section>
172 <div data-testid="query-status">query: ${query.status}</div>
173 <div data-testid="mutation-status">mutation: ${mutation.status}</div>
174 <div data-testid="active-fetches">fetches: ${this.isFetching()}</div>
175 <div data-testid="active-mutations">
176 mutations: ${this.isMutating()}
177 </div>
178 <div data-testid="request-count">
179 server-requests: ${query.data?.requestCount ?? 0}
180 </div>
181 <div data-testid="data-source">
182 source: ${query.data?.source ?? 'none'}
183 </div>
184 </section>
185β
186 <section>
187 <button
188 data-testid="refetch"
189 @click=${() => this.todosQuery.refetch()}
190 >
191 Refetch
192 </button>
193 <button
194 data-testid="invalidate"
195 @click=${() => this.invalidateTodos()}
196 >
197 Invalidate
198 </button>
199 <button
200 data-testid="seed-cache"
201 @click=${() => this.seedCacheOnlyTodo()}
202 >
203 Seed Cache
204 </button>
205 <button
206 data-testid="reset-demo-state"
207 @click=${() => this.resetDemoState()}
208 >
209 Reset Demo State
210 </button>
211 <button
212 data-testid="fail-next-fetch"
213 @click=${() => this.forceNextFetchFailure()}
214 >
215 Fail Next Fetch
216 </button>
217 <button
218 data-testid="fail-next-mutation"
219 @click=${() => this.forceNextMutationFailure()}
220 >
221 Fail Next Mutation
222 </button>
223 </section>
224β
225 <section>
226 <label for="newTodoInput">New todo</label>
227 <input
228 id="newTodoInput"
229 data-testid="new-todo-input"
230 .value=${this.nextTodoTitle}
231 @input=${this.onTitleInput}
232 />
233 <button data-testid="add-todo" @click=${() => this.addTodo()}>
234 Add Todo (Mutation)
235 </button>
236 </section>
237β
238 ${
239 query.isError
240 ? html`<div data-testid="query-error">${String(query.error)}</div>`
241 : null
242 }
243 ${
244 mutation.isError
245 ? html`<div data-testid="mutation-error">
246 ${String(mutation.error)}
247 </div>`
248 : null
249 }
250β
251 <ul data-testid="todo-list">
252 ${todos.map(
253 (todo) =>
254 html`<li data-testid="todo-item">${todo.id}: ${todo.title}</li>`,
255 )}
256 </ul>
257 </main>
258 `
259 }
260}
261β
262customElements.define('tanstack-lit-query-demo', TanstackLitQueryDemo)
263β
264class DemoRoot extends LitElement {
265 protected override createRenderRoot(): HTMLElement | DocumentFragment {
266 return this
267 }
268β
269 render() {
270 return html`
271 <demo-query-provider>
272 <tanstack-lit-query-demo></tanstack-lit-query-demo>
273 </demo-query-provider>
274 `
275 }
276}
277β
278customElements.define('demo-root', DemoRoot)