GraphQL

· abundance's blog


Because React Query's fetching mechanisms are agnostically built on Promises, you can use React Query with literally any asynchronous data fetching client, including GraphQL!

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!

Type-Safety and Code Generation #

React Query, used in combination with graphql-request^5 and GraphQL Code Generator provides full-typed GraphQL operations:

 1import request from 'graphql-request'
 2import { useQuery } from '@tanstack/react-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          id
12          title
13        }
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}

You can find a complete example in the repo

Get started with the dedicated guide on GraphQL Code Generator documentation.