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

queries.md

117 lines4.3 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```tsx
18import { useQuery } from '@tanstack/react-query'
19​
20function App() {
21 const info = useQuery(['todos'], fetchTodoList)
23```
24​
25The **unique key** you provide is used internally for refetching, caching, and sharing your queries throughout your application.
26​
27The query results returned by `useQuery` contains all of the information about the query that you'll need for templating and any other usage of the data:
28​
29```tsx
30const result = useQuery(['todos'], fetchTodoList)
31```
32​
33The `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:
34​
35- `isLoading` or `status === 'loading'` - The query has no data yet
36- `isError` or `status === 'error'` - The query encountered an error
37- `isSuccess` or `status === 'success'` - The query was successful and data is available
38​
39Beyond those primary states, more information is available depending on the state of the query:
40​
41- `error` - If the query is in an `isError` state, the error is available via the `error` property.
42- `data` - If the query is in a `success` state, the data is available via the `data` property.
43​
44For **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:
45​
46```tsx
47function Todos() {
48 const { isLoading, isError, data, error } = useQuery(['todos'], fetchTodoList)
49​
50 if (isLoading) {
51 return <span>Loading...</span>
52 }
53​
54 if (isError) {
55 return <span>Error: {error.message}</span>
56 }
57​
58 // We can assume by this point that `isSuccess === true`
59 return (
60 <ul>
61 {data.map(todo => (
62 <li key={todo.id}>{todo.title}</li>
63 ))}
64 </ul>
65 )
67```
68​
69If booleans aren't your thing, you can always use the `status` state as well:
70​
71```tsx
72function Todos() {
73 const { status, data, error } = useQuery(['todos'], fetchTodoList)
74​
75 if (status === 'loading') {
76 return <span>Loading...</span>
77 }
78​
79 if (status === 'error') {
80 return <span>Error: {error.message}</span>
81 }
82​
83 // also status === 'success', but "else" logic works, too
84 return (
85 <ul>
86 {data.map(todo => (
87 <li key={todo.id}>{todo.title}</li>
88 ))}
89 </ul>
90 )
92```
93​
94TypeScript will also narrow the type of `data` correctly if you've checked for `loading` and `error` before accessing it.
95​
96### FetchStatus
97​
98In addition to the `status` field, the `result` object, you will also get an additional `fetchStatus`property with the following options:
99​
100- `fetchStatus === 'fetching'` - The query is currently fetching.
101- `fetchStatus === 'paused'` - The query wanted to fetch, but it is paused. Read more about this in the [Network Mode](../guides/network-mode) guide.
102- `fetchStatus === 'idle'` - The query is not doing anything at the moment.
103​
104### Why two different states?
105​
106Background refetches and stale-while-revalidate logic make all combinations for `status` and `fetchStatus` possible. For example:
107- a query in `success` status will usually be in `idle` fetchStatus, but it could also be in `fetching` if a background refetch is happening.
108- 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.
109​
110So keep in mind that a query can be in `loading` state without actually fetching data. As a rule of thumb:
111​
112- The `status` gives information about the `data`: Do we have any or not?
113- The `fetchStatus` gives information about the `queryFn`: Is it running or not?
114​
115## Further Reading
116​
117For an alternative way of performing status checks, have a look at the [Community Resources](../community/tkdodos-blog#4-status-checks-in-react-query).