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

basic-query.ts

90 lines2.1 KB

1import { LitElement, html } from 'lit'
2import {
3 QueryClient,
4 QueryClientProvider,
5 createQueryController,
6} from '@tanstack/lit-query'
7import { fetchTodosFromServer, resetTodoApi } from './todoApi'
8import type { TodosResponse } from './todoApi'
9​
10resetTodoApi()
11​
12const queryClient = new QueryClient({
13 defaultOptions: {
14 queries: { retry: false },
15 },
16})
17​
18class BasicQueryProvider extends QueryClientProvider {
19 constructor() {
20 super()
21 this.client = queryClient
22 }
23​
24 protected override createRenderRoot(): HTMLElement | DocumentFragment {
25 return this
26 }
28​
29customElements.define('basic-query-provider', BasicQueryProvider)
30​
31class BasicQueryExample extends LitElement {
32 private readonly todos = createQueryController<TodosResponse, Error>(this, {
33 queryKey: ['todos'],
34 queryFn: fetchTodosFromServer,
35 })
36​
37 protected override createRenderRoot(): HTMLElement | DocumentFragment {
38 return this
39 }
40​
41 render() {
42 const query = this.todos()
43 return html`
44 <main>
45 <h1>Basic Query Example</h1>
46 <p data-testid="basic-query-status">
47 Status: <strong>${query.status}</strong>
48 </p>
49 <button
50 data-testid="basic-refetch"
51 @click=${() => this.todos.refetch()}
52 >
53 Refetch
54 </button>
55​
56 ${query.isPending
57 ? html`<p data-testid="basic-loading">Loading...</p>`
58 : null}
59 ${query.isError
60 ? html`<p data-testid="basic-error">Error: ${String(query.error)}</p>`
61 : null}
62​
63 <ul data-testid="basic-todo-list">
64 ${(query.data?.items ?? []).map(
65 (todo) =>
66 html`<li data-testid="basic-todo-item">${todo.title}</li>`,
67 )}
68 </ul>
69 </main>
70 `
71 }
73​
74customElements.define('basic-query-example', BasicQueryExample)
75​
76class BasicQueryRoot extends LitElement {
77 protected override createRenderRoot(): HTMLElement | DocumentFragment {
78 return this
79 }
80​
81 render() {
82 return html`
83 <basic-query-provider>
84 <basic-query-example></basic-query-example>
85 </basic-query-provider>
86 `
87 }
89​
90customElements.define('basic-query-root', BasicQueryRoot)