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```js
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```js
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```js
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 and while not always necessary, this makes it possible to extract your query functions if needed:
51β
52```js
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## Using a Query Object instead of parameters
65β
66Anywhere the `[queryKey, queryFn, config]` signature is supported throughout React Query's API, you can also use an object to express the same configuration:
67β
68```js
69import { useQuery } from 'react-query'
70β
71useQuery({
72 queryKey: ['todo', 7],
73 queryFn: fetchTodo,
74 ...config,
75})
76```