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

query-functions.md

81 lines1.5 KB

1---
2id: query-functions
3title: Query Functions
4ref: docs/framework/react/guides/query-functions.md
5---
6​
7[//]: # 'Example'
8​
9```tsx
10useQuery(() => ({ queryKey: ['todos'], queryFn: fetchAllTodos }))
11useQuery(() => ({
12 queryKey: ['todos', todoId],
13 queryFn: () => fetchTodoById(todoId),
14}))
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[//]: # 'Example2'
30​
31```tsx
32const todosQuery = useQuery(() => ({
33 queryKey: ['todos', todoId],
34 queryFn: async () => {
35 if (somethingGoesWrong) {
36 throw new Error('Oh no!')
37 }
38 if (somethingElseGoesWrong) {
39 return Promise.reject(new Error('Oh no!'))
40 }
41​
42 return data
43 },
44}))
45```
46​
47[//]: # 'Example2'
48[//]: # 'Example3'
49​
50```tsx
51useQuery(() => ({
52 queryKey: ['todos', todoId],
53 queryFn: async () => {
54 const response = await fetch('/todos/' + todoId)
55 if (!response.ok) {
56 throw new Error('Network response was not ok')
57 }
58 return response.json()
59 },
60}))
61```
62​
63[//]: # 'Example3'
64[//]: # 'Example4'
65​
66```tsx
67function Todos(props) {
68 const todosQuery = useQuery(() => ({
69 queryKey: ['todos', { status: props.status, page: props.page }],
70 queryFn: fetchTodoList,
71 }))
73​
74// Access the key, status and page variables in your query function!
75function fetchTodoList({ queryKey }) {
76 const [_key, { status, page }] = queryKey
77 return new Promise()
79```
80​
81[//]: # 'Example4'