Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

main.ts

272 lines6.8 KB

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