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

queries.md

149 lines4.7 KB

1---
2id: queries
3title: Queries
4---
5​
6## Query Basics
7​
8A query is a declarative dependency on an asynchronous source of data that is tied to a **unique key**. A query can be used with any Promise based method (including GET and POST methods) to fetch data from a server. If your method modifies data on the server, we recommend using [Mutations](./mutations.md) instead.
9​
10[//]: # 'SubscribeDescription'
11​
12To subscribe to a query in your components or custom hooks, call the `useQuery` hook with at least:
13​
14[//]: # 'SubscribeDescription'
15​
16- A **unique key for the query**
17- A function that returns a promise that:
18 - Resolves the data, or
19 - Throws an error
20​
21[//]: # 'Example'
22​
23```tsx
24import { useQuery } from '@tanstack/react-query'
25​
26function App() {
27 const info = useQuery({ queryKey: ['todos'], queryFn: fetchTodoList })
29```
30​
31[//]: # 'Example'
32​
33The **unique key** you provide is used internally for refetching, caching, and sharing your queries throughout your application.
34​
35The query result returned by `useQuery` contains all of the information about the query that you'll need for templating and any other usage of the data:
36​
37[//]: # 'Example2'
38​
39```tsx
40const result = useQuery({ queryKey: ['todos'], queryFn: fetchTodoList })
41```
42​
43[//]: # 'Example2'
44​
45The `result` object contains a few very important states you'll need to be aware of to be productive. A query can only be in one of the following states at any given moment:
46​
47- `isPending` or `status === 'pending'` - The query has no data yet
48- `isError` or `status === 'error'` - The query encountered an error
49- `isSuccess` or `status === 'success'` - The query was successful and data is available
50​
51Beyond those primary states, more information is available depending on the state of the query:
52​
53- `error` - If the query is in an `isError` state, the error is available via the `error` property.
54- `data` - If the query is in an `isSuccess` state, the data is available via the `data` property.
55- `isFetching` - In any state, if the query is fetching at any time (including background refetching) `isFetching` will be `true`.
56​
57For **most** queries, it's usually sufficient to check for the `isPending` state, then the `isError` state, then finally, assume that the data is available and render the successful state:
58​
59[//]: # 'Example3'
60​
61```tsx
62function Todos() {
63 const { isPending, isError, data, error } = useQuery({
64 queryKey: ['todos'],
65 queryFn: fetchTodoList,
66 })
67​
68 if (isPending) {
69 return <span>Loading...</span>
70 }
71​
72 if (isError) {
73 return <span>Error: {error.message}</span>
74 }
75​
76 // We can assume by this point that `isSuccess === true`
77 return (
78 <ul>
79 {data.map((todo) => (
80 <li key={todo.id}>{todo.title}</li>
81 ))}
82 </ul>
83 )
85```
86​
87[//]: # 'Example3'
88​
89If booleans aren't your thing, you can always use the `status` state as well:
90​
91[//]: # 'Example4'
92​
93```tsx
94function Todos() {
95 const { status, data, error } = useQuery({
96 queryKey: ['todos'],
97 queryFn: fetchTodoList,
98 })
99​
100 if (status === 'pending') {
101 return <span>Loading...</span>
102 }
103​
104 if (status === 'error') {
105 return <span>Error: {error.message}</span>
106 }
107​
108 // also status === 'success', but "else" logic works, too
109 return (
110 <ul>
111 {data.map((todo) => (
112 <li key={todo.id}>{todo.title}</li>
113 ))}
114 </ul>
115 )
117```
118​
119[//]: # 'Example4'
120​
121TypeScript will also narrow the type of `data` correctly if you've checked for `pending` and `error` before accessing it.
122​
123### FetchStatus
124​
125In addition to the `status` field, you will also get an additional `fetchStatus` property with the following options:
126​
127- `fetchStatus === 'fetching'` - The query is currently fetching.
128- `fetchStatus === 'paused'` - The query wanted to fetch, but it is paused. Read more about this in the [Network Mode](./network-mode.md) guide.
129- `fetchStatus === 'idle'` - The query is not doing anything at the moment.
130​
131### Why two different states?
132​
133Background refetches and stale-while-revalidate logic make all combinations for `status` and `fetchStatus` possible. For example:
134​
135- a query in `success` status will usually be in `idle` fetchStatus, but it could also be in `fetching` if a background refetch is happening.
136- a query that mounts and has no data will usually be in `pending` status and `fetching` fetchStatus, but it could also be `paused` if there is no network connection.
137​
138So keep in mind that a query can be in `pending` state without actually fetching data. As a rule of thumb:
139​
140- The `status` gives information about the `data`: Do we have any or not?
141- The `fetchStatus` gives information about the `queryFn`: Is it running or not?
142​
143[//]: # 'Materials'
144​
145## Further Reading
146​
147For an alternative way of performing status checks, have a look at [this article by TkDodo](https://tkdodo.eu/blog/status-checks-in-react-query).
148​
149[//]: # 'Materials'