How to use GraphQL Code Generator with React Query
19 July 2022
GraphQL is a great way to build apps faster. But, if you're using GraphQL without a GraphQL Code Generator (codegen) you're missing out on the full potential of GraphQL in your development setup.
In this blog post, you'll learn how to use the missing piece (GraphQL Code Generator) to unleash the full potential of GraphQL with React, React Query v4, and TypeScript.
Using GraphQL Code Generator, we'll generate Typed Queries, Mutations, and, Subscriptions. This will enable us to have up-to-date typings and autocompletion on all queries, mutations, and, subscription variables and results in our code.
Let's get started.
Setup
Three simple steps are required to set up GraphQL Code Generator:
- Install a few npm packages.
- Create a GraphQL Code Generator configuration file.
- Add a GraphQL Code Generator script to the
package.json
file.
Install NPM packages
Install the following npm packages required to run GraphQL Code Generator.
npm install graphql
npm install -D typescript @graphql-codegen/cli @graphql-codegen/client-preset @graphql-typed-document-node/core
# or yarn
yarn add graphql
yarn add -D typescript @graphql-codegen/cli @graphql-codegen/client-preset @graphql-typed-document-node/core
# or pnpm
pnpm add graphql
pnpm add -D typescript @graphql-codegen/cli @graphql-codegen/client-preset @graphql-typed-document-node/core
Create a Config File for GraphQL Code Generator
Next, create a codegen.ts
configuration file next to your package.json
file.
This configuration file contains information about:
- GraphQL API URL.
- GraphQL API headers.
- Where GraphQL queries and mutations exist in your code.
Update the file with your GraphQL endpoint and headers. Here's an example:
import { CodegenConfig } from '@graphql-codegen/cli'
const config: CodegenConfig = {
schema: [
{
'http://localhost:1337/v1/graphql': {
headers: {
'x-hasura-admin-secret': 'nhost-admin-secret',
},
},
},
],
ignoreNoDocuments: true,
generates: {
'./src/gql/': {
documents: ['src/**/*.tsx'],
preset: 'client',
plugins: [],
},
},
}
export default config
This example configuration file is for a Nhost project using Hasura. We've set the GraphQL endpoint to http://localhost:1337/v1/graphql
and added the x-hasura-admin-secret
header so the GraphQL Code Generator can introspect the GraphQL API as an admin to get all queries and mutations available.
GraphQL autocomplete in VS Code
This step is optional but highly recommended.
You can get autocomplete when writing GraphQL queries and mutations in VS Code. This is another great way to improve your development workflow and reduce errors caused by typos.
To get inline autocomplete when you're writing GraphQL in VS Code, install the GraphQL for VSCode extension and add the following configuration (graphql.config.yaml
) file next to your package.json
file:
schema:
- http://localhost:1337/v1/graphql:
headers:
x-hasura-admin-secret: nhost-admin-secret
Add a Codegen Script to package.json
As the last step, add a script to the package.json
to run the GraphQL Code Generator.
{
/*...*/
"scripts": {
/*...*/
"codegen": "graphql-codegen"
}
/*...*/
}
You'll run this script (npm run codegen
) every time you've changed anything in your GraphQL API or in your GraphQL files to get the most up-to-date types generated. You can also run the script in watch mode to automatically generate new types when you change your code using npm run codegen -w
.
You've now completed the three configuration steps. It's time to start using the GraphQL Code Generator and unleash its power!
Workflow
As a mental model, this is how you will use the GraphQL Code Generator in your development workflow:
- Run
npm run codegen -w
in watch mode to automatically generate types for queries, mutations, and subscriptions. - Write GraphQL queries and mutations and wrap the GraphQL code with the
graphql()
function. - Use the generated types to get autocompletion and type safety.
The graphql()
function is generated by the GraphQL Code Generator and located at src/gql/gql
.
Here's an example of how to write a GraphQL query and wrap it with the graphql()
function:
import { graphql } from '../gql/gql'
const GET_TASKS = graphql(`
query GetTasks {
tasks(order_by: { createdAt: desc }) {
id
name
done
}
}
`)
Example: Todo App
We'll now go through two examples of how to use the GraphQL Code Generator setup with React Query in a Todo App. The first example is by using a query to fetch data and the other example is to use a mutation to modify data.
The full source code can be found on GitHub - GraphQL Code Generator Example with React Query. This blog post contains a subset of the code to give you a basic understanding of how to use GraphQL Code Generator with React Query.
For the two examples, we're using a table tasks
in Hasura with three columns:
- id - UUID
- name - Text
- done - Boolean
App Setup
Install React Query and graphql-request.
npm install @tanstack/react-query graphql-request
# or yarn
yarn add @tanstack/react-query graphql-request
# or pnpm
pnpm add @tanstack/react-query graphql-request
Why do we install graphql-request?
React Query is agnostic to how data is queried and mutated. We need to implement the
queryFn
andmutationFn
ourselves. We'll use graphql-request to send the GraphQL requests.
Let's continue by first setting up the React Query client in our app. After that, we'll configure the graphql-request client.
React Query Client
In src/utils/react-query-client.ts
we create a QueryClient
that is used by React Query.
import { QueryClient } from '@tanstack/react-query'
export const queryClient = new QueryClient()
GraphQL Client
In src/utils/graphql-client.ts
we create our GraphQL client using graphql-request. In this example, we're adding an authorization header using the Nhost JavaScript client.
import { nhost } from './nhost'
import { GraphQLClient } from 'graphql-request'
type AuthHeaderProps = {
authorization?: string
}
export const gqlClient = new GraphQLClient(nhost.graphql.getUrl(), {
headers: () => {
const authHeaders = {} as AuthHeaderProps
if (nhost.auth.isAuthenticated()) {
authHeaders['authorization'] = `Bearer ${nhost.auth.getAccessToken()}`
}
return {
'Content-Type': 'application/json',
...authHeaders,
}
},
})
App
React Query requires a QueryClient
and a QueryClientProvider
. This is how to set it up in e.g. App.tsx
:
import { QueryClientProvider } from '@tanstack/react-query'
import { queryClient } from './utils/react-query-client'
import { Tasks } from './components/Tasks'
function App() {
return (
<QueryClientProvider client={queryClient}>
<div>
<div>Todo App</div>
<Tasks />
</div>
</QueryClientProvider>
)
}
export default App
Get Tasks (GraphQL Query)
As we mentioned under the Workflow section above, we use the three-step process when using GraphQL Code Generator.
Just to repeat, these are the three steps:
- Run
npm run codegen -w
in watch mode to automatically generate types for GraphQL queries, mutations, and subscriptions. - Write GraphQL queries and mutations and wrap the GraphQL code with the
graphql()
function. - Use the generated types to get autocompletion and type safety.
Let's get going.
Run the codegen to automatically generate types:
npm run codegen -w
Next, we'll combine the graphql()
function with the useQuery()
and GraphQL Request hook to fetch the data.
import { useMutation, useQuery } from '@tanstack/react-query'
import { graphql } from '../gql/gql'
import { gqlClient } from '../utils/graphql-client'
const GET_TASKS = graphql(`
query GetTasks {
tasks(order_by: { createdAt: desc }) {
id
name
done
}
}
`)
export function Tasks() {
const { data, isLoading, isError, error } = useQuery({
queryKey: ['tasks'],
queryFn: async () => {
return gqlClient.request(GET_TASKS)
},
})
if (isLoading) {
return <div>Loading...</div>
}
if (isError) {
console.error(error)
return <div>Error</div>
}
if (!data) {
return <div>No data</div>
}
const { tasks } = data
return (
<div>
<h2>Todos</h2>
<ul>
{tasks.map((task) => (
<li key={task.id}>{task.name}</li>
))}
</ul>
</div>
)
}
That's it. In this scenario, using Nhost, you now have type-safety from Postgres, to GraphQL to TypeScript. From your database to your frontend. Good job!
Now, let's see some benefits of this setup!
If you're trying to access a property on tasks
that does not exist, TypeScript will throw an error. E.g. if you're trying to access task.age
.
src/components/Tasks.tsx:160:44 - error TS2339: Property 'age' does not exist on type '{ __typename?: "tasks" | undefined; id: any; name: string; done: boolean; }'.
160 <div className={style}>{task.age}</div>
~~~
Found 1 error in src/components/Tasks.tsx:160
NOTE: If you're using Vite remember that Vite does not perform type checking. You need to run
tsc -noEmit
to see any TypeScript errors.
If you're using VS Code you also see the TypeScript error while you're coding:
TypeScript also knows that task.name
is of type string
, which it has inferred from Postgres ( the task.name
column is of type text
) and GraphQL (task.name
is of type String
). This means you can't use task.name
to perform arithmetic operations.
As you see, with the GraphQL Code Generator (and Postgres, GraphQL, and TypeScript) you're less likely to run into type errors. Overall, your application becomes more robust with fewer bugs.
Let's continue and see how to use GraphQL Code Generator with GraphQL mutations.
Insert Task (Mutation)
Specify the GraphQL mutation and wrap it around the graphql()
function.
Next, specify the mutation in the useMutation
hook. The mutationFn
is the function that will be called when the mutation is triggered. If the mutation is successful, the onSuccess
function will be called where we invalidate the tasks
query to refetch the data.
Now you can use the insertTask
function to trigger the mutation.
import { useState } from 'react'
import { useMutation, useQuery } from '@tanstack/react-query'
import { graphql } from '../gql/gql'
import { gqlClient } from '../utils/graphql-client'
import { queryClient } from '../utils/react-query-client'
const INSERT_TASK = graphql(`
mutation InsertTask($task: tasks_insert_input!) {
insertTasks(objects: [$task]) {
affected_rows
returning {
id
name
}
}
}
`)
export function NewTask() {
const [name, setName] = useState('')
const insertTask = useMutation({
mutationFn: (name: string) => {
return gqlClient.request(INSERT_TASK, {
task: {
name,
},
})
},
onSuccess: () => {
queryClient.invalidateQueries(['tasks'])
},
})
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
if (!name) {
return
}
try {
await insertTask.mutate(name)
setName('')
alert('Task added!')
} catch (error) {
return console.error(error)
}
}
return (
<div>
<h2>New Task</h2>
<div>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label
htmlFor="email"
className="block text-sm font-medium text-gray-700"
>
Todo
</label>
<div className="mt-1">
<input
type="text"
placeholder="Todo"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
</div>
{isError && <div>Error: {JSON.stringify(error, null, 2)}</div>}
<div>
<button type="submit" disabled={insertTask.isLoading}>
Add
</button>
</div>
</form>
</div>
</div>
)
}
GitHub Repository
The example code for this blog post is on GitHub - GraphQL Code Generator Example with React Query.
Summary
That's it. You've now a basic understanding of how to set up and use GraphQL Code Generator with React Query. This will help you build robust applications with fewer bugs. Good luck!
What's next?
Did you enjoy this blog post?