GraphQL
由于 Preact Query 的拉取机制基于 Promise 构建,且与具体实现无关,因此你可以将 Preact Query 与任何异步数据拉取客户端(包括 GraphQL)配合使用!
请注意:Preact Query 不支持规范化缓存(normalized caching)。虽然绝大多数用户实际上并不需要规范化缓存,甚至未必能从中获得预期的收益,但在极少数特殊场景下,规范化缓存可能确实必要——因此请务必先与我们确认,确保这确实是你的实际需求!
类型安全与代码生成
Preact Query 结合 graphql-request^5 和 GraphQL Code Generator,可为 GraphQL 操作提供完整的类型支持:
TypeScript
1import request from 'graphql-request'2import { useQuery } from '@tanstack/preact-query'3 4import { graphql } from './gql/gql'5 6const allFilmsWithVariablesQueryDocument = graphql(/* GraphQL */ `7 query allFilmsWithVariablesQuery($first: Int!) {8 allFilms(first: $first) {9 edges {10 node {11 id12 title13 }14 }15 }16 }17`)18 19function App() {20 // `data` is fully typed!21 const { data } = useQuery({22 queryKey: ['films'],23 queryFn: async () =>24 request(25 'https://swapi-graphql.netlify.app/.netlify/functions/index',26 allFilmsWithVariablesQueryDocument,27 // variables are type-checked too!28 { first: 10 },29 ),30 })31 // ...32}你可以在 仓库中找到完整示例
请参考 GraphQL Code Generator 文档中的专用指南 快速上手。