GraphQL Codegen Typed Document Nodes

Generate fully typed GraphQL document nodes with codegen, so queries, variables, and result shapes are checked before runtime execution.

TypescriptReactData Fetching

Code

typescriptsnippet
43 lines
import { useQuery } from '@apollo/client';
import { graphql } from '../generated/gql';

// 代码生成物由 graphql-codegen 从 schema 产出:
// const LeaderboardQuery = graphql(`
//   query Leaderboard($region: Region!) {
//     leaderboard(region: $region) {
//       rank
//       player { name }
//       score
//     }
//   }
// `);

const LeaderboardQuery = graphql(`
  query Leaderboard($region: Region!) {
    leaderboard(region: $region) {
      rank
      player { name }
      score
    }
  }
`);

function Leaderboard({ region }: { region: 'eu' | 'na' }) {
  const { data, loading, error } = useQuery(LeaderboardQuery, {
    variables: { region },
    fetchPolicy: 'cache-first',
  });

  if (loading) return <p>loading…</p>;
  if (error) return <p role="alert">failed to load leaderboard</p>;

  return (
    <ol>
      {data?.leaderboard.map((row) => (
        <li key={row.rank}>
          {row.player.name} — {row.score}
        </li>
      ))}
    </ol>
  );
}

How it works

GraphQL Codegen Typed Document Nodes keeps everything in the function Leaderboard.

useQuery, graphql are the only symbols borrowed from @apollo/client — the coupling is explicit and narrow.

Points of care

  • Plan for an install step: @apollo/client is a real dependency, resolved by the package manager.
  • The guard loading short-circuits the flow with an early return when its condition holds.

Putting it to use

The primary signature is function Leaderboard({ region }: { region: 'eu' | 'na' })

Core lines

{data?.leaderboard.map((row) => (
  <li key={row.rank}>
    {row.player.name} — {row.score}
  </li>
))}
if (error) return <p role="alert">failed to load leaderboard</p>;
if (loading) return <p>loading…</p>;

Interactive Tools for This Topic

FAQ

Which packages must be installed first?
Yes. The imports resolve to `@apollo/client`, which the package manager must provide.