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

query-functions.md

76 lines2.3 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​
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)
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()
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```