Open History to see the last commit
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 }
36}
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>`
75}
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 `
108}
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 }))
128}
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).