框架
版本

查询函数

查询函数可以是任何返回 Promise 的函数。返回的 Promise 应该解析数据抛出错误

以下所有都是有效的查询函数配置

tsx
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。查询函数中抛出的任何错误都将持久化到查询的 error 状态。

tsx
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
  },
})

fetch 和其他默认不抛出错误的客户端一起使用

虽然像 axiosgraphql-request 这样的大多数实用程序会自动为不成功的 HTTP 调用抛出错误,但像 fetch 这样的一些实用程序默认情况下不会抛出错误。如果是这种情况,您需要自己抛出错误。以下是使用流行的 fetch API 执行此操作的简单方法

tsx
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()
  },
})

查询函数变量

查询键不仅用于唯一标识您正在获取的数据,而且还方便地作为 QueryFunctionContext 的一部分传递到您的查询函数中。虽然并非总是必要,但这使得在需要时可以提取您的查询函数

tsx
function Todos({ status, page }) {
  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()
}
function Todos({ status, page }) {
  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

QueryFunctionContext 是传递给每个查询函数的对象。它包含:

  • queryKey: QueryKey: 查询键
  • client: QueryClient: QueryClient
  • signal?: AbortSignal
  • meta: Record<string, unknown> | undefined
    • 一个可选字段,您可以用关于查询的附加信息填充它

此外,无限查询 获取以下传递的选项

  • pageParam: TPageParam
    • 用于获取当前页面的页面参数
  • direction: 'forward' | 'backward'
    • 已弃用
    • 当前页面获取的方向
    • 要访问当前页面获取的方向,请从 getNextPageParamgetPreviousPageParampageParam 添加方向。