React Query in SSR starring Graphql-Codegen

What makes Graphql more awesome?

Consider the below type Character.

Repository

Find the repository for finished code below.

Create a new next app.

npx create-next-app --ts

Install dependencies

npm i graphql
npm i -D @graphql-codegen/cli

Initialize the project

npx graphql-codegen init

Answer a few simple questions

Legacy peer dependency

While installing the dependencies with npm i, You may encounter the Could not resolve dependency problem with the version of graphql.

npm i --legacy-peer-deps

Install React Query

The official documentation of graphql-codegen plugin for the react-query is elaborate. Check that out for more details.

npm i react-query
npm i -D @graphql-codegen/typescript-react-query

Update Codegen.yml

Update the codegen.yml file in the root to resemble the below.

  • exposeQueryKeys: This property enables .getKey(). We use it as the key for the react query without having to manually give a string.
  • Content-Type fetchParams: The Content-Type by default is set to text/html for the response header and text/plain for the request. That will get us the POST body missing. Did you forget use body-parser middleware? error. So update this to application/json.
  • pureMagicComment: This is to enforce tree-shaking.

Sample query

Create a query.graphql file. You can name this anything you want as long as it matches src/**/*.graphql that we provided in the documents field in codegen.yml.

Generate!

Execute the below command to see your types and react query hooks generated for us!

npm run gql:codegen// ornpx graphql-codegen --config codegen.yml

React Query — Hydrate

React query suggests two ways to query data in SSR. Read about that in detail here.

React Querying in getStaticProps

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Karthick Ragavendran

Karthick Ragavendran

Fullstack engineer @ atem.green | React, Typescript, Redux, JavaScript, UI, Storybook, CSS, UX, Cypress, CI/CD.