DEV Community

alex-vladut
alex-vladut

Posted on

How to generate Typescript types for GraphQL queries in a React app

In this article, we'll walk you through the steps for updating the configuration of a frontend React app to generate Typescript types for GraphQL queries based on your API schema. By the end of this tutorial, you'll be able to import .graphql files and get fully typed data returned by useQuery so that your IDE can show you autocomplete suggestions for the fields that can be accessed.

To get started, create a simple React application named users using Vite for running and building the app. You can create it any way you want (e.g. CRA or Next.js).

Let's start by defining the type of experience we would like to have, and then we'll work our way up to adding all the configuration in place.

Create a GraphQL file named getUser.graphql and add the following query to it:

query User($id: ID!) {
  getUser(id: $id) {
    id
    name
  }
}
Enter fullscreen mode Exit fullscreen mode

Next, create a simple React component that will fetch the user and display their name.

import { useQuery } from '@apollo/client';

import { UserDocument } from './getUser.graphql';

type Props = {
  id: string
}

export function User({ id }: Props) {
  const { data, loading, error } = useQuery(UserDocument, { variables: { id } });

  if (loading) return <Spinner />;
  if (error) return <Error />;

  return <span>{data.getUser.name}</span>;
}
Enter fullscreen mode Exit fullscreen mode

For this example, we are using the Apollo GraphQL client, but the same example will work just fine with any other client (e.g. URQL) that supports TypeDocumentNodes.

To enable such a development experience, we need to install the following NPM dependencies:

npm i -D @lente/vite-plugin-graphql @graphql-codegen/typescript-operations @graphql-codegen/typed-document-node @babel/preset-typescript @babel/preset-react
Enter fullscreen mode Exit fullscreen mode

At the top level of your project, add a .graphql-let.yml file with the following content:

schema:
  - schema.graphql

documents:
  - '**/*.graphql'

plugins:
  - typescript-operations
  - typed-document-node
Enter fullscreen mode Exit fullscreen mode

Under the hood, @lente/vite-plugin-graphql uses graphql-let, and .graphql-let.yml is where we define where the GraphQL schema is located and how to identify the GraphQL files to be parsed. Check out this repo for more details on the options available https://github.com/piglovesyou/graphql-let.

Finally, add the configuration to vite.config.ts for loading the .graphql files:

import { defineConfig } from 'vite';

import graphql from '@lente/vite-plugin-graphql';

export default defineConfig({
  ...
  plugins: [
    ...
    graphql({
      include: /\.(graphqls?|gql)$/i,
      babel: {
        presets: ['@babel/preset-typescript', '@babel/preset-react'],
      },
      rootContext: __dirname, // path to directory containing `graphql-let.yml`
    }),
  ],
  ...
});
Enter fullscreen mode Exit fullscreen mode

Now you can start the application, and it should automatically parse the GraphQL files and generate the corresponding types.

You can check out this GitHub repository https://github.com/alex-vladut/vite-graphql-example.

Top comments (0)