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

graphql.md

54 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 { useQuery } from '@tanstack/react-query'
18import request from 'graphql-request'
19import { graphql } from './gql/gql'
20​
21const allFilmsWithVariablesQueryDocument = graphql(/* GraphQL */ `
22 query allFilmsWithVariablesQuery($first: Int!) {
23 allFilms(first: $first) {
24 edges {
25 node {
26 id
27 title
28 }
29 }
30 }
31 }
32`)
33​
34function App() {
35 // `data` is fully typed!
36 const { data } = useQuery({
37 queryKey: ['films'],
38 queryFn: async () =>
39 request(
40 'https://swapi-graphql.netlify.app/.netlify/functions/index',
41 allFilmsWithVariablesQueryDocument,
42 // variables are type-checked too!
43 { first: 10 },
44 ),
45 })
46 // ...
48```
49​
50_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)_
51​
52Get started with the [dedicated guide on GraphQL Code Generator documentation](https://www.the-guild.dev/graphql/codegen/docs/guides/react-vue).
53​
54[//]: # 'Codegen'