Frontend app doesn't know anything about the schema that backend GraphQL API is using.
You can create type definitions for the GraphQL schema, but if the schema changes in the future, you have to remember to update our frontend as well; this means that our frontend's TypeScript types can easily get out of sync.
yarn add graphql yarn add --dev typescript @graphql-codegen/cli
Setup:
// codegen.ts import type { CodegenConfig } from '@graphql-codegen/cli' const config: CodegenConfig = { schema: 'https://localhost:4000/graphql', documents: ['src/**/*.tsx'], generates: { './src/gql/': { preset: 'client', } } } export default config
Using React query:
// import { request } from 'graphql-request' import { useQuery } from '@tanstack/react-query' import { graphql } from './gql/gql' const postsQueryDocument = graphql(/* GraphQL */ ` query Posts { posts { id title author { id firstName lastName } } } `) const Posts = () => { const { data } = useQuery<PostsQuery>('posts', async () => { const { posts } = await request(endpoint, postsQueryDocument) return posts }) // `data` is fully typed! // … }