Open History to see the last commit
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 }))
72}
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()
78}
79```
80β
81[//]: # 'Example4'