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

queries.md

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