loading...

Create products index page

notrab profile image Jamie Barton ・1 min read

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
        }
      }
    }
  }
`;

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
  }
}

Then where we have:

price {
  formatted_with_symbol
}

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

...PriceInfo

Discussion

pic
Editor guide