Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

graphql.md

55 lines1.8 KB

1---
2id: graphql
3title: GraphQL
4---
5​
6Because React Query's fetching mechanisms are agnostically built on Promises, you can use React Query with literally any asynchronous data fetching client, including GraphQL!
7​
8> Keep in mind that React Query does not support normalized caching. While a vast majority of users do not actually need a normalized cache or even benefit from it as much as they believe they do, there may be very rare circumstances that may warrant it so be sure to check with us first to make sure it's truly something you need!
9​
10[//]: # 'Codegen'
11​
12## Type-Safety and Code Generation
13​
14React Query, used in combination with `graphql-request^5` and [GraphQL Code Generator](https://graphql-code-generator.com/) provides full-typed GraphQL operations:
15​
16```tsx
17import request from 'graphql-request'
18import { useQuery } from '@tanstack/react-query'
19​
20import { graphql } from './gql/gql'
21​
22const allFilmsWithVariablesQueryDocument = graphql(/* GraphQL */ `
23 query allFilmsWithVariablesQuery($first: Int!) {
24 allFilms(first: $first) {
25 edges {
26 node {
27 id
28 title
29 }
30 }
31 }
32 }
33`)
34​
35function App() {
36 // `data` is fully typed!
37 const { data } = useQuery({
38 queryKey: ['films'],
39 queryFn: async () =>
40 request(
41 'https://swapi-graphql.netlify.app/.netlify/functions/index',
42 allFilmsWithVariablesQueryDocument,
43 // variables are type-checked too!
44 { first: 10 },
45 ),
46 })
47 // ...
49```
50​
51_You can find a [complete example in the repo](https://github.com/dotansimha/graphql-code-generator/tree/7c25c4eeb77f88677fd79da557b7b5326e3f3950/examples/front-end/react/tanstack-react-query)_
52​
53Get started with the [dedicated guide on GraphQL Code Generator documentation](https://www.the-guild.dev/graphql/codegen/docs/guides/react-vue).
54​
55[//]: # 'Codegen'