框架
版本

GraphQL

由于 React Query 的获取机制是基于 Promise 构建的,因此你可以将 React Query 与几乎任何异步数据获取客户端一起使用,包括 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 },
      ),
  })
  // ...
}

你可以在 repo 中的完整示例 中找到一个完整的示例

请参阅 GraphQL Code Generator 文档上的专用指南,开始使用。