GraphQL Codegen Typed Document Nodes
Generate fully typed GraphQL document nodes with codegen, so queries, variables, and result shapes are checked before runtime execution.
Code
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/clientis a real dependency, resolved by the package manager. - The guard
loadingshort-circuits the flow with an earlyreturnwhen 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
GraphQL SDL to TypeScript ConverterParse GraphQL SDL type, input, interface, enum, union, and scalar definitions into strict TypeScript interfaces and literal unions locally.GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.JSON to TypeScriptGenerate TypeScript interface and type declarations from a sample JSON payload, inferring primitives, arrays, and nested object shapes automatically.JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.
FAQ
- Which packages must be installed first?
- Yes. The imports resolve to `@apollo/client`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.