Hit the Ground Running with GraphQL Codegen and WooGraphQL

Geoff Taylor
By Geoff Taylor
2 years ago
Hit the Ground Running with GraphQL Codegen and WooGraphQL

Photo by Jayson Hinrichsen on Unsplash

In this tutorial, we will guide you through using GraphQL-Codegen and WPGraphQL/WooGraphQL to create a simple product page for your WordPress-powered eCommerce site. We will be focusing on generating TypeScript type definitions and React components for queries and mutations with the help of GraphQL-Codegen's typescript and react-typescript plugins.

We will create a step-by-step case study to demonstrate the process of creating a product page that retrieves data using WooGraphQL. By the end of this tutorial, you will have a better understanding of how to use GraphQL-Codegen and WPGraphQL/WooGraphQL to build efficient and flexible eCommerce applications.

Prerequisites

  • A WordPress site with WPGraphQL and WooGraphQL plugins installed and activated
  • A basic understanding of GraphQL and React

Step 1: Install GraphQL-Codegen and required plugins

First, let's install GraphQL-Codegen and the required plugins:

npm install --save-dev @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/react-typescript

Step 2: Configure GraphQL-Codegen

Create a codegen.yml file in the root of your project with the following content:

schema: 'https://your-wordpress-site.com/graphql'
documents: './src/**/*.graphql'
generates:
  ./src/generated/graphql.tsx:
    plugins:
      - typescript
      - react-typescript

Replace https://your-wordpress-site.com/graphql with the URL of your WordPress site's GraphQL endpoint.

Step 3: Create a .graphql file for your query

Create a src/queries directory and a GetProduct.graphql file inside it:

query GetProduct($id: ID!) {
  product(id: $id) {
    id
    name
    description
    image {
      sourceUrl
    }
    ... on SimpleProduct {
      isOnSale
      regularPrice
      salePrice
    }
    ... on VariableProduct {
      isOnSale
      regularPrice
      salePrice
    }
  }
}

This query fetches the product data, including the name, description, image, regular price, and sale price.

Step 4: Generate TypeScript types and React components

Run the following command to generate the TypeScript types and React components:

npx graphql-codegen

The generated graphql.tsx file will be located in the ./src/generated directory.

Step 5: Create the product page component

Now, let's create a product page component that uses the generated React components and types:

import { GetProduct } from '../generated/graphql';
import { useQuery } from '@apollo/client';

function ProductPage({ productId }) {
  const { loading, error, data } = useQuery(GetProduct, {
    variables: { id: productId },
  });

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  const { product } = data;

  return (
    <div>
      <h1>{product.name}</h1>
      <img src={product.image.sourceUrl} alt={product.name} />
      <p>{product.description}</p>
      {product.isOnSale ? (
        <p>
          <del>{product.regularPrice}</del> {product.salePrice}
        </p>
      ) : (
        <p>{product.regularPrice}</p
      )}
    </div>
  );
}

The ProductPage component receives the productId as a prop and uses the useQuery hook from Apollo Client to fetch the product data using the GetProduct query. It then displays the product name, image, description, and price, along with the sale price if available.

Step 6: Integrate the ProductPage component into your application

Now you can import and use the ProductPage component in your application. Pass the productId prop with the desired product's ID, and the component will display the product details.

Wrapping Up

Congratulations! You have successfully used GraphQL-Codegen and WPGraphQL/WooGraphQL to create a simple product page for your WordPress-powered eCommerce site. By leveraging the power of GraphQL and TypeScript, you have made your application more efficient and flexible.

In the next post, we will cover creating the add to cart button and its functionality, including how to handle products already in the shopping cart. Stay tuned!