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β
8All of the following are valid query function configurations:
9β
10[//]: # 'Example'
11β
12```tsx
13useQuery({ queryKey: ['todos'], queryFn: fetchAllTodos })
14useQuery({ queryKey: ['todos', todoId], queryFn: () => fetchTodoById(todoId) })
15useQuery({
16 queryKey: ['todos', todoId],
17 queryFn: async () => {
18 const data = await fetchTodoById(todoId)
19 return data
20 },
21})
22useQuery({
23 queryKey: ['todos', todoId],
24 queryFn: ({ queryKey }) => fetchTodoById(queryKey[1]),
25})
26```
27β
28[//]: # 'Example'
29β
30## Handling and Throwing Errors
31β
32For 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.
33β
34[//]: # 'Example2'
35β
36```tsx
37const { error } = useQuery({
38 queryKey: ['todos', todoId],
39 queryFn: async () => {
40 if (somethingGoesWrong) {
41 throw new Error('Oh no!')
42 }
43 if (somethingElseGoesWrong) {
44 return Promise.reject(new Error('Oh no!'))
45 }
46β
47 return data
48 },
49})
50```
51β
52[//]: # 'Example2'
53β
54## Usage with `fetch` and other clients that do not throw by default
55β
56While 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:
57β
58[//]: # 'Example3'
59β
60```tsx
61useQuery({
62 queryKey: ['todos', todoId],
63 queryFn: async () => {
64 const response = await fetch('/todos/' + todoId)
65 if (!response.ok) {
66 throw new Error('Network response was not ok')
67 }
68 return response.json()
69 },
70})
71```
72β
73[//]: # 'Example3'
74β
75## Query Function Variables
76β
77Query 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:
78β
79[//]: # 'Example4'
80β
81```tsx
82function Todos({ status, page }) {
83 const result = useQuery({
84 queryKey: ['todos', { status, page }],
85 queryFn: fetchTodoList,
86 })
87}
88β
89// Access the key, status and page variables in your query function!
90function fetchTodoList({ queryKey }) {
91 const [_key, { status, page }] = queryKey
92 return new Promise()
93}
94```
95β
96[//]: # 'Example4'
97β
98### QueryFunctionContext
99β
100The `QueryFunctionContext` is the object passed to each query function. It consists of:
101β
102- `queryKey: QueryKey`: [Query Keys](./query-keys.md)
103- `client: QueryClient`: [QueryClient](../../../reference/QueryClient.md)
104- `signal?: AbortSignal`
105 - [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) instance provided by TanStack Query
106 - Can be used for [Query Cancellation](./query-cancellation.md)
107- `meta: Record<string, unknown> | undefined`
108 - an optional field you can fill with additional information about your query
109β
110Additionally, [Infinite Queries](./infinite-queries.md) get the following options passed:
111β
112- `pageParam: TPageParam`
113 - the page parameter used to fetch the current page
114- `direction: 'forward' | 'backward'`
115 - **deprecated**
116 - the direction of the current page fetch
117 - To get access to the direction of the current page fetch, please add a direction to `pageParam` from `getNextPageParam` and `getPreviousPageParam`.