Skip to content
This repository has been archived by the owner on Apr 13, 2023. It is now read-only.

feat: Added helping generic types for hooks #3726

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

lucasconstantino
Copy link

When using TypeScript and code generation tools for GraphQL query typings, the use of hooks such as useQuery can become very bloated with long generics, and what should probably a simple one liner gets quite hard to read, specially with multiple hooks (many mutations, for instance).

No TypeScript:

import { useQuery } from '@apollo/react-hooks'

const HelloWorld = ({ name }) => {
  const { data, loading } = useQuery(HELLO_WORLD_QUERY, { variables: { name } })

  return loading ? 'loading' : <p>{data.hello}</p>
}

Typescript:

import { useQuery } from '@apollo/react-hooks'

import {
  HELLO_WORLD_QUERY_DATA,
  HELLO_WORLD_QUERY_VARIABLES,
} from './generated-types'

const HelloWorld: React.FC<{ name: string }> = ({ name }) => {
  const { data, loading } = useQuery<
    HELLO_WORLD_QUERY_DATA,
    HELLO_WORLD_QUERY_VARIABLES
  >(HELLO_WORLD_QUERY, { variables: { name } })

  return loading ? 'loading' : <p>{data.hello}</p>
}

What this pull-request does is export a generic type to allow typing of queries/mutations before we use hooks. Outcome could be something like this:

TypeScript with UseQuery/UseMutation/UseSubscription:

import { useQuery, UseQuery } from '@apollo/react-hooks'

import {
  HELLO_WORLD_QUERY_DATA,
  HELLO_WORLD_QUERY_VARIABLES,
} from './generated-types'

const useHelloWorld: UseQuery<
  HELLO_WORLD_QUERY_DATA,
  HELLO_WORLD_QUERY_VARIABLES
> = useQuery

const HelloWorld: React.FC<{ name: string }> = ({ name }) => {
  const { data, loading } = useHelloWorld(HELLO_WORLD_QUERY, { variables: { name } })

  return loading ? 'loading' : <p>{data.hello}</p>
}

As can be seen, this makes it easier to reduce complexity and code within the component itself, while moving static non-variable procedures such as typing outside the business code.

Ps.: some may say this is already possible by creating a secondary hook, which is a similar solution, but the solution with helper types guarantees we have same APIs available with no need to create new interfaces due to custom hooks argument types.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant