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```tsx
11useQuery(['todos'], fetchAllTodos)
12useQuery(['todos', todoId], () => fetchTodoById(todoId))
13useQuery(['todos', todoId], async () => {
14 const data = await fetchTodoById(todoId)
15 return data
16})
17useQuery(['todos', todoId], ({ queryKey }) => fetchTodoById(queryKey[1]))
18```
19β
20## Handling and Throwing Errors
21β
22For React Query to determine a query has errored, the query function **must throw**. Any error that is thrown in the query function will be persisted on the `error` state of the query.
23β
24```tsx
25const { error } = useQuery(['todos', todoId], async () => {
26 if (somethingGoesWrong) {
27 throw new Error('Oh no!')
28 }
29β
30 return data
31})
32```
33β
34## Usage with `fetch` and other clients that do not throw by default
35β
36While 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:
37β
38```tsx
39useQuery(['todos', todoId], async () => {
40 const response = await fetch('/todos/' + todoId)
41 if (!response.ok) {
42 throw new Error('Network response was not ok')
43 }
44 return response.json()
45})
46```
47β
48## Query Function Variables
49β
50Query 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:
51β
52```tsx
53function Todos({ status, page }) {
54 const result = useQuery(['todos', { status, page }], fetchTodoList)
55}
56β
57// Access the key, status and page variables in your query function!
58function fetchTodoList({ queryKey }) {
59 const [_key, { status, page }] = queryKey
60 return new Promise()
61}
62```
63β
64### QueryFunctionContext
65β
66The `QueryFunctionContext` is the object passed to each query function. It consists of:
67β
68- `queryKey: QueryKey`: [Query Keys](../guides/query-keys)
69- `pageParam: unknown | undefined`
70 - only for [Infinite Queries](../guides/infinite-queries)
71 - the page parameter used to fetch the current page
72- signal?: AbortSignal
73 - [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) instance provided by react-query
74 - Can be used for [Query Cancellation](../guides/query-cancellation)
75- `meta?: Record<string, unknown>`
76 - an optional field you can fill with additional information about your query
77β
78## Using a Query Object instead of parameters
79β
80Anywhere the `[queryKey, queryFn, config]` signature is supported throughout React Query's API, you can also use an object to express the same configuration:
81β
82```tsx
83import { useQuery } from '@tanstack/react-query'
84β
85useQuery({
86 queryKey: ['todo', 7],
87 queryFn: fetchTodo,
88 ...config,
89})
90```