Open History to see the last commit
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 })
89}
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()
95}
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`.