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

queries.md

141 lines4.1 KB

1---
2id: queries
3title: Queries
4---
5​
6New to Lit Query? Start with [Installation](../installation.md) and [Quick Start](../quick-start.md) before wiring query controllers into your elements.
7​
8## Query Basics
9​
10A query is a declarative dependency on an asynchronous source of data tied to a unique key. Use queries for reading server state. If a function creates, updates, or deletes server data, use a [mutation](./mutations.md) instead.
11​
12In Lit, subscribe to a query with [`createQueryController`](../reference/functions/createQueryController.md):
13​
14```ts
15import { LitElement, html } from 'lit'
16import { createQueryController } from '@tanstack/lit-query'
17​
18class TodosView extends LitElement {
19 private readonly todos = createQueryController(this, {
20 queryKey: ['todos'],
21 queryFn: fetchTodos,
22 })
23​
24 render() {
25 const query = this.todos()
26​
27 if (query.isPending) return html`Loading...`
28 if (query.isError) return html`Error: ${query.error.message}`
29​
30 return html`
31 <ul>
32 ${query.data.map((todo) => html`<li>${todo.title}</li>`)}
33 </ul>
34 `
35 }
37```
38​
39The controller needs:
40​
41- A `ReactiveControllerHost`, usually `this` inside a `LitElement`
42- A unique `queryKey`
43- A `queryFn` that returns a promise and throws on errors
44​
45The returned accessor exposes the current `QueryObserverResult`. Call it in `render`, or read `.current`:
46​
47```ts
48const query = this.todos()
49const sameQuery = this.todos.current
50```
51​
52## Query States
53​
54A query can be in one primary state at a time:
55​
56- `isPending` or `status === 'pending'`: no data is available yet
57- `isError` or `status === 'error'`: the query failed and `error` is available
58- `isSuccess` or `status === 'success'`: data is available
59​
60The result also includes `isFetching`, which can be true during the initial load or a background refetch.
61​
62```ts
63render() {
64 const query = this.todos()
65​
66 if (query.status === 'pending') {
67 return html`<span>Loading...</span>`
68 }
69​
70 if (query.status === 'error') {
71 return html`<span>Error: ${query.error.message}</span>`
72 }
73​
74 return html`<todo-list .items=${query.data}></todo-list>`
76```
77​
78TypeScript will narrow `query.data` after you check `pending` and `error` before reading it.
79​
80## Fetch Status
81​
82The `status` field describes whether data is available. The `fetchStatus` field describes what the query function is doing:
83​
84- `fetchStatus === 'fetching'`: the query is currently fetching.
85- `fetchStatus === 'paused'`: the query wanted to fetch, but fetching is paused.
86- `fetchStatus === 'idle'`: the query is not fetching.
87​
88These states are intentionally separate. Background refetching and stale-while-revalidate behavior can produce combinations like:
89​
90- A successful query with cached data can have `status === 'success'` and `fetchStatus === 'fetching'` while a background refetch is running.
91- A query with no data can have `status === 'pending'` and `fetchStatus === 'paused'` if fetching cannot start yet.
92​
93Use `status` when deciding whether data can be rendered, and use `fetchStatus` or `isFetching` when deciding whether to show a network activity indicator:
94​
95```ts
96render() {
97 const query = this.todos()
98​
99 if (query.isPending) return html`Loading...`
100 if (query.isError) return html`Error: ${query.error.message}`
101​
102 return html`
103 ${query.fetchStatus === 'fetching'
104 ? html`<span>Refreshing...</span>`
105 : null}
106 <todo-list .items=${query.data}></todo-list>
107 `
109```
110​
111## Reactive Query Options
112​
113Use an options getter when the query key or query function depends on host state:
114​
115```ts
116class UserTodos extends LitElement {
117 static properties = {
118 userId: { type: String },
119 }
120​
121 userId = ''
122​
123 private readonly todos = createQueryController(this, () => ({
124 queryKey: ['todos', this.userId],
125 queryFn: () => fetchTodos(this.userId),
126 enabled: this.userId.length > 0,
127 }))
129```
130​
131The query key is used for caching, refetching, and sharing data between controllers.
132​
133## Refetching
134​
135The accessor includes `refetch`:
136​
137```ts
138html`<button @click=${() => this.todos.refetch()}>Refetch</button>`
139```
140​
141For multiple queries that should run at the same time, see [Parallel Queries](./parallel-queries.md).