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

query-functions.md

79 lines1.5 KB

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(() => ({
12 queryKey: ['todos', todoId],
13 queryFn: () => fetchTodoById(todoId),
14}))
15injectQuery(() => ({
16 queryKey: ['todos', todoId],
17 queryFn: async () => {
18 const data = await fetchTodoById(todoId)
19 return data
20 },
21}))
22injectQuery(() => ({
23 queryKey: ['todos', todoId],
24 queryFn: ({ queryKey }) => fetchTodoById(queryKey[1]),
25}))
26```
27​
28[//]: # 'Example'
29[//]: # 'Example2'
30​
31```ts
32todoQuery = injectQuery(() => ({
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```ts
51todoQuery = injectQuery(() => ({
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```ts
67todosQuery = injectQuery(() => ({
68 queryKey: ['todos', { status: status(), page: page() }],
69 queryFn: fetchTodoList,
70}))
71​
72// Access the key, status and page variables in your query function!
73function fetchTodoList({ queryKey }) {
74 const [_key, { status, page }] = queryKey
75 return new Promise()
77```
78​
79[//]: # 'Example4'