DEV Community

Jamie Barton
Jamie Barton

Posted on

Create products index page

Let's now create the /products page for browsing just our products.

Create the file src/pages/products.js, and add the following:

import React from "react";
import { graphql } from "gatsby";

import ProductList from "../components/ProductList";

export default function ProductsPage({ data: { allChecProduct } }) {
  return (
    <React.Fragment>
      <h1>Products</h1>

      <ProductList products={allChecProduct.nodes} />
    </React.Fragment>
  );
}

export const pageQuery = graphql`
  query ProductsPageQuery {
    allChecProduct {
      nodes {
        name
        permalink
        price {
          formatted_with_symbol
        }
      }
    }
  }
`;
Enter fullscreen mode Exit fullscreen mode

Similar to the homepage, we export a pageQuery that queries allChecProduct. You will notice a bit of repetition for our query here.

Let's assume the products index page will in the future show more than just the name and permalink, so we'll keep this query defined here, but let's turn the price query into a GraphQL Fragment.

GraphQL Fragments mean we can define a name for our query, and use that fragment instead of typing again what fields we want from price.

Inside the pageQuery of src/pages/index.js, add the following fragment:

fragment PriceInfo on ChecProduct {
  price {
    formatted_with_symbol
  }
}
Enter fullscreen mode Exit fullscreen mode

Then where we have:

price {
  formatted_with_symbol
}
Enter fullscreen mode Exit fullscreen mode

In both src/pages/index.js, and src/pages/products.js, replace it with:

...PriceInfo
Enter fullscreen mode Exit fullscreen mode

Discussion (0)