Working with TypeScript, React and Apollo Client

Working with TypeScript, React and Apollo Client

In this guide we'll explore working with the generated types with React and Apollo Client.

You should already have the GraphQL Code Generator setup and watching for any changes to your application — do this first before you continue reading.

Let's begin by installing Apollo Client:

npm install -D @apollo/client graphql

So we can use useQuery with the generated types we can now pass it our generated TypedDocumentNode that we generated in another guide.

You should by this point have the folder ./gql (or whatever you named it) somewhere in your project that we can import graphql from.

Let's imagine the following code is your frontend application where you want to invoke useQuery to fetch from your Grafbase backend:

import { graphql } from '../gql' const GetAllPostsDocument = graphql(/* GraphQL */ ` query GetAllPosts { postCollection(first: 10) { edges { node { title published author { name } } } } } `)

GraphQL Code Generator will generate a TypedDocumentNode that we can pass to useQuery without having to import anything else!

You can pass GetAllPostsDocument to useQuery and get full type-safety in your frontend!

import { useQuery } from '@apollo/client' import { graphql } from '../gql' const GetAllPostsDocument = graphql(/* GraphQL */ ` query GetAllPosts { postCollection(first: 10) { edges { node { title published author { name } } } } } `) const Page = () => { const { data } = useQuery(GetAllPostsDocument) return <pre>{JSON.stringify(data, null, 2)}</pre> }

That's it! The object data above is fully typed!

Where variables are used you can update the query to define those variables:

import { graphql } from '../gql' const GetAllPostsDocument = graphql(/* GraphQL */ ` query GetAllPosts($first: Int!) { postCollection(first: $first) { edges { node { title published author { name } } } } } `)

Then when used with useQuery you will have a typed variables object:

const Page = () => { const { data } = useQuery(GetAllPostsDocument, { variables: { first: 10 } }) return <pre>{JSON.stringify(data, null, 2)}</pre> }

You can learn more about TypeScript and Apollo Client by visiting their documentation.

Build your next Apollo Client backend with Grafbase

Get early access to the Grafbase beta.