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