查询函数可以是任何返回 Promise 的函数。返回的 Promise 应当解析数据 (resolve the data) 或抛出错误 (throw an error)。
以下都是有效的查询函数配置方式:
useQuery({ queryKey: ['todos'], queryFn: fetchAllTodos })
useQuery({ queryKey: ['todos', todoId], queryFn: () => fetchTodoById(todoId) })
useQuery({
queryKey: ['todos', todoId],
queryFn: async () => {
const data = await fetchTodoById(todoId)
return data
},
})
useQuery({
queryKey: ['todos', todoId],
queryFn: ({ queryKey }) => fetchTodoById(queryKey[1]),
})
useQuery({ queryKey: ['todos'], queryFn: fetchAllTodos })
useQuery({ queryKey: ['todos', todoId], queryFn: () => fetchTodoById(todoId) })
useQuery({
queryKey: ['todos', todoId],
queryFn: async () => {
const data = await fetchTodoById(todoId)
return data
},
})
useQuery({
queryKey: ['todos', todoId],
queryFn: ({ queryKey }) => fetchTodoById(queryKey[1]),
})
为了让 TanStack Query 判定查询发生了错误,查询函数必须抛出错误或返回一个被拒绝的 Promise (rejected Promise)。在查询函数中抛出的任何错误都会被持久化到查询的 error 状态中。
const { error } = useQuery({
queryKey: ['todos', todoId],
queryFn: async () => {
if (somethingGoesWrong) {
throw new Error('Oh no!')
}
if (somethingElseGoesWrong) {
return Promise.reject(new Error('Oh no!'))
}
return data
},
})
const { error } = useQuery({
queryKey: ['todos', todoId],
queryFn: async () => {
if (somethingGoesWrong) {
throw new Error('Oh no!')
}
if (somethingElseGoesWrong) {
return Promise.reject(new Error('Oh no!'))
}
return data
},
})
虽然大多数工具如 axios 或 graphql-request 会自动为不成功的 HTTP 调用抛出错误,但像 fetch 这样的工具默认不会抛出错误。如果是这种情况,你需要自行抛出错误。以下是使用流行的 fetch API 实现这一点的简单方法:
useQuery({
queryKey: ['todos', todoId],
queryFn: async () => {
const response = await fetch('/todos/' + todoId)
if (!response.ok) {
throw new Error('Network response was not ok')
}
return response.json()
},
})
useQuery({
queryKey: ['todos', todoId],
queryFn: async () => {
const response = await fetch('/todos/' + todoId)
if (!response.ok) {
throw new Error('Network response was not ok')
}
return response.json()
},
})
查询键 (Query keys) 不仅用于唯一标识你要获取的数据,还会作为 QueryFunctionContext 的一部分方便地传递到你的查询函数中。虽然并非总是必要,但这使得在需要时可以提取查询函数:
const result = useQuery({
queryKey: ['todos', { status, page }],
queryFn: fetchTodoList,
})
// Access the key, status and page variables in your query function!
function fetchTodoList({ queryKey }) {
const [_key, { status, page }] = queryKey
return new Promise()
}
const result = useQuery({
queryKey: ['todos', { status, page }],
queryFn: fetchTodoList,
})
// Access the key, status and page variables in your query function!
function fetchTodoList({ queryKey }) {
const [_key, { status, page }] = queryKey
return new Promise()
}
QueryFunctionContext 是传递给每个查询函数的对象,包含以下属性:
此外,无限查询 (Infinite Queries) 还会传递以下选项: