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

basic-query.ts

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