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

query-functions.md

119 lines3.9 KB

1---
2id: query-functions
3title: Query Functions
4---
5​
6A query function can be literally any function that **returns a promise**. The promise that is returned should either **resolve the data** or **throw an error**.
7​
8On success, the resolved value may be anything **except `undefined`**. Queries that resolve to `undefined` will be [treated as failed](https://tanstack.com/query/latest/docs/framework/react/guides/migrating-to-react-query-4#undefined-is-an-illegal-cache-value-for-successful-queries). To store "nothing" as a successful result in the query cache, resolve `null` instead.
9​
10All of the following are valid query function configurations:
11​
12[//]: # 'Example'
13​
14```tsx
15useQuery({ queryKey: ['todos'], queryFn: fetchAllTodos })
16useQuery({ queryKey: ['todos', todoId], queryFn: () => fetchTodoById(todoId) })
17useQuery({
18 queryKey: ['todos', todoId],
19 queryFn: async () => {
20 const data = await fetchTodoById(todoId)
21 return data
22 },
23})
24useQuery({
25 queryKey: ['todos', todoId],
26 queryFn: ({ queryKey }) => fetchTodoById(queryKey[1]),
27})
28```
29​
30[//]: # 'Example'
31​
32## Handling and Throwing Errors
33​
34For TanStack Query to determine a query has errored, the query function **must throw** or return a **rejected Promise**. Any error that is thrown in the query function will be persisted on the `error` state of the query.
35​
36[//]: # 'Example2'
37​
38```tsx
39const { error } = useQuery({
40 queryKey: ['todos', todoId],
41 queryFn: async () => {
42 if (somethingGoesWrong) {
43 throw new Error('Oh no!')
44 }
45 if (somethingElseGoesWrong) {
46 return Promise.reject(new Error('Oh no!'))
47 }
48​
49 return data
50 },
51})
52```
53​
54[//]: # 'Example2'
55​
56## Usage with `fetch` and other clients that do not throw by default
57​
58While most utilities like `axios` or `graphql-request` automatically throw errors for unsuccessful HTTP calls, some utilities like `fetch` do not throw errors by default. If that's the case, you'll need to throw them on your own. Here is a simple way to do that with the popular `fetch` API:
59​
60[//]: # 'Example3'
61​
62```tsx
63useQuery({
64 queryKey: ['todos', todoId],
65 queryFn: async () => {
66 const response = await fetch('/todos/' + todoId)
67 if (!response.ok) {
68 throw new Error('Network response was not ok')
69 }
70 return response.json()
71 },
72})
73```
74​
75[//]: # 'Example3'
76​
77## Query Function Variables
78​
79Query keys are not just for uniquely identifying the data you are fetching, but are also conveniently passed into your query function as part of the QueryFunctionContext. While not always necessary, this makes it possible to extract your query functions if needed:
80​
81[//]: # 'Example4'
82​
83```tsx
84function Todos({ status, page }) {
85 const result = useQuery({
86 queryKey: ['todos', { status, page }],
87 queryFn: fetchTodoList,
88 })
90​
91// Access the key, status and page variables in your query function!
92function fetchTodoList({ queryKey }) {
93 const [_key, { status, page }] = queryKey
94 return new Promise()
96```
97​
98[//]: # 'Example4'
99​
100### QueryFunctionContext
101​
102The `QueryFunctionContext` is the object passed to each query function. It consists of:
103​
104- `queryKey: QueryKey`: [Query Keys](./query-keys.md)
105- `client: QueryClient`: [QueryClient](../reference/classes/QueryClient.md)
106- `signal?: AbortSignal`
107 - [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) instance provided by TanStack Query
108 - Can be used for [Query Cancellation](./query-cancellation.md)
109- `meta: Record<string, unknown> | undefined`
110 - an optional field you can fill with additional information about your query
111​
112Additionally, [Infinite Queries](./infinite-queries.md) get the following options passed:
113​
114- `pageParam: TPageParam`
115 - the page parameter used to fetch the current page
116- `direction: 'forward' | 'backward'`
117 - **deprecated**
118 - the direction of the current page fetch
119 - To get access to the direction of the current page fetch, please add a direction to `pageParam` from `getNextPageParam` and `getPreviousPageParam`.