框架
版本

GraphQL

因为 React Query 的数据获取机制是基于 Promise 构建的,所以你可以将其与任何异步数据获取客户端一起使用,包括 GraphQL!

请记住,React Query 不支持规范化缓存。虽然绝大多数用户实际上并不需要规范化缓存,甚至从中受益不如他们认为的那么多,但极少数情况下可能需要它,因此请务必先与我们核实,以确保它确实是您需要的东西!

类型安全和代码生成

React Query 与 graphql-request^5GraphQL Code Generator 结合使用,可提供完全类型化的 GraphQL 操作。

tsx
import request from 'graphql-request'
import { useQuery } from '@tanstack/react-query'

import { graphql } from './gql/gql'

const allFilmsWithVariablesQueryDocument = graphql(/* GraphQL */ `
  query allFilmsWithVariablesQuery($first: Int!) {
    allFilms(first: $first) {
      edges {
        node {
          id
          title
        }
      }
    }
  }
`)

function App() {
  // `data` is fully typed!
  const { data } = useQuery({
    queryKey: ['films'],
    queryFn: async () =>
      request(
        'https://swapi-graphql.netlify.app/.netlify/functions/index',
        allFilmsWithVariablesQueryDocument,
        // variables are type-checked too!
        { first: 10 },
      ),
  })
  // ...
}
import request from 'graphql-request'
import { useQuery } from '@tanstack/react-query'

import { graphql } from './gql/gql'

const allFilmsWithVariablesQueryDocument = graphql(/* GraphQL */ `
  query allFilmsWithVariablesQuery($first: Int!) {
    allFilms(first: $first) {
      edges {
        node {
          id
          title
        }
      }
    }
  }
`)

function App() {
  // `data` is fully typed!
  const { data } = useQuery({
    queryKey: ['films'],
    queryFn: async () =>
      request(
        'https://swapi-graphql.netlify.app/.netlify/functions/index',
        allFilmsWithVariablesQueryDocument,
        // variables are type-checked too!
        { first: 10 },
      ),
  })
  // ...
}

你可以在 仓库中找到完整示例

GraphQL Code Generator 文档中的专用指南 开始。