Open History to see the last commit
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 })
24}
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- `isPending` or `status === 'pending'` - 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 `isPending` 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 { isPending, isError, data, error } = useQuery({
59 queryKey: ['todos'],
60 queryFn: fetchTodoList,
61 })
62β
63 if (isPending) {
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 )
79}
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 === 'pending') {
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 )
111}
112```
113β
114[//]: # 'Example4'
115β
116TypeScript will also narrow the type of `data` correctly if you've checked for `pending` 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 `pending` 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 `pending` 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'