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

query-functions.md

117 lines3.5 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[//]: # '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 })
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()
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`.