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>
);
}Report a problem with this exampleOpens a pre-filled issue on GitHub.