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```ts
10injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchAllTodos }))
11injectQuery(() => ({ queryKey: ['todos', todoId], queryFn: () => fetchTodoById(todoId) })
12injectQuery(() => ({
13 queryKey: ['todos', todoId],
14 queryFn: async () => {
15 const data = await fetchTodoById(todoId)
16 return data
17 },
18}))
19injectQuery(() => ({
20 queryKey: ['todos', todoId],
21 queryFn: ({ queryKey }) => fetchTodoById(queryKey[1]),
22}))
23```
24β
25[//]: # 'Example'
26[//]: # 'Example2'
27β
28```ts
29todos = injectQuery(() => ({
30 queryKey: ['todos', todoId()],
31 queryFn: async () => {
32 if (somethingGoesWrong) {
33 throw new Error('Oh no!')
34 }
35 if (somethingElseGoesWrong) {
36 return Promise.reject(new Error('Oh no!'))
37 }
38β
39 return data
40 },
41}))
42```
43β
44[//]: # 'Example2'
45[//]: # 'Example3'
46β
47```ts
48todos = injectQuery(() => ({
49 queryKey: ['todos', todoId()],
50 queryFn: async () => {
51 const response = await fetch('/todos/' + todoId)
52 if (!response.ok) {
53 throw new Error('Network response was not ok')
54 }
55 return response.json()
56 },
57}))
58```
59β
60[//]: # 'Example3'
61[//]: # 'Example4'
62β
63```ts
64result = injectQuery(() => ({
65 queryKey: ['todos', { status: status(), page: page() }],
66 queryFn: fetchTodoList,
67}))
68β
69// Access the key, status and page variables in your query function!
70function fetchTodoList({ queryKey }) {
71 const [_key, { status, page }] = queryKey
72 return new Promise()
73}
74```
75β
76[//]: # 'Example4'