DEV Community

Cover image for Generating TypeScript types and React Hooks based on a GraphQL endpoint
Danilo Woznica
Danilo Woznica

Posted on • Updated on • Originally published at danilowoz.com

Generating TypeScript types and React Hooks based on a GraphQL endpoint

Cover image by Fred Jesus

Nowadays, developing ReactJS with TypeScript gives us a solid way to write applications: it adds the advantage of type-safety, component auto-documentation, error handling, and accurate autocomplete in the editor code. However, it still requires a considerable effort to write types and keep them maintainable. Moreover, when the data provider is a GraphQL server, it makes you feel like you're doing a useless job, given the server already has its own schemas for types. Seem redundant, right?

With this in mind, GraphQL Code Generator gives us the ability to generate TypesScript typing out of GraphQL schemas. Beyond that, it gives us a couple of plugins to create custom React hooks that don't require any kind of maintenance or workaround to fit into your application.

Among many others, some of the benefits of using this tool:

  • Codeless: forget about creating the interfaces/types for every GraphQL endpoints; save time and spend effort on what matters;
  • Development experience: as a result of having the types always available, your editor will provide meaningful autocomplete and error checking;
  • Types always up-to-date: if your GraphQL endpoint schemas change, your application will be updated and typescript will help you make sure you make the necessary changes.

Setup

First of all, let's install the dependencies needed:

npm i @apollo/react-hooks graphql
Enter fullscreen mode Exit fullscreen mode
npm i @graphql-codegen/cli @graphql-codegen/import-types-preset @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo --save-dev
Enter fullscreen mode Exit fullscreen mode

I'm considering the following folder structure, but of course, feel free to adapt it to your liking, just have in mind that it needs a place to store the schemas that will be fetched by the Code Generator:

📦 my-project
┣ 📂 src
┃ ┣ 📂 pages
┃ ┃ ┗ index.tsx
┃ ┣ 📂 queries
┃ ┃ ┣ 📂 autogenerate
┃ ┃ ┗ my-query.gql
┃ ┗ apollo-client.ts
┣ codegen.yml
â”— package.json
Enter fullscreen mode Exit fullscreen mode

Then, basically, you'll need to create a configuration file at the root of the project, named codegen.yml. The following snippet shows how I usually set it up in my projects, where it generates different files for its own purpose, in other words, split by concerns like GraphQL operations and server schemas:

# Endpoint API, the following URL is a example
schema: https://countries-274616.ew.r.appspot.com/graphql/
overwrite: true
# Format files
hooks:
  afterAllFileWrite:
    - prettier --write
generates:
  # Get schemas from server
  src/queries/autogenerate/schemas.tsx:
    documents: 'src/queries/**/**.gql'
    plugins:
      - typescript
  # Create operations based on queries
  src/queries/autogenerate/operations.tsx:
    documents: 'src/queries/**/**.gql'
    preset: import-types
    presetConfig:
      typesPath: ./schemas
    plugins:
      - typescript-operations
  # 1. Export GraphQL documents
  # 2. React interface
  src/queries/autogenerate/hooks.tsx:
    documents: 'src/queries/**/**.gql'
    preset: import-types
    presetConfig:
      typesPath: ./operations
    plugins:
      - typescript-react-apollo
    config:
      # Optionals
      withHOC: false
      withComponent: false
      withHooks: true
Enter fullscreen mode Exit fullscreen mode

Also, let's add the scripts to generate the schemas and watch the files change in package.json:

"scripts": {
  ...
  "schemas": "graphql-codegen --config codegen.yml",
  "schemas:watch": "npm run schemas -- --watch",
},
Enter fullscreen mode Exit fullscreen mode

And as it turns out in the editor code:
Live coding

This is only one of the possible ways to use it, as it has many plugins, presets, integrations, and configurations, for different purposes such as to generate React higher-order component, Gatsby integration, prettier and lint the files, among other cool things. Feel free to check out the documentation here.

I've made a repository available with the code above, and you can check it out here.


Originally published at danilowoz.com


Top comments (0)