Today I Learned

Use GraphQL schema to create TS types and react hooks

Very often when working with backend it is useful for frontend application to know what response can we get.

When working with TypeScript we can actually generate types and hooks using schema.graphql or even “live” backend.

This is where graphql-codegen comes in handy

When you need to create generic components for resources (types) shared across different components you can use typescript plugin

When writing graphql queries, you can also generate type-safe react hooks with typescript-react-apollo plugin. With this plugin you only need to write *.graphql with desired Query, Mutation, Subscription or Fragment (you don’t need to import fragments in your quries!) and respective hooks will be created.

Example configuration codegen.yaml file from project:

overwrite: true

schema: 'http://localhost:4000/graphql'

documents:
  - 'src/**/queries.ts'
  - 'src/**/*.graphql'

generates:
  src/__generated__/types.tsx:
    plugins:
      - 'typescript'
    config:
      maybeValue: T | undefined

  src/__generated__/operations.tsx:
    preset: import-types
    presetConfig:
      typesPath: ./types
    plugins:
      - typescript-operations
    config:
      maybeValue: T | undefined

  src/__generated__/hooks.tsx:
    preset: import-types
    presetConfig:
      typesPath: ./operations
    plugins:
      - typescript-react-apollo
    config:
      maybeValue: T | undefined