Skip to main content

Attempting to handle dynamic schema types in Gatsby GraphQL queries

Published on

Well. I had a great idea to use Gatsby's StaticQuery component for catalogs and product displays. I was hoping to also use the useStaticQuery hook for experimenting with shadowing. There is just one problem. When you try to use string interpolation with Gatsby, things explode.

String interpolation is not allowed in graphql tag:

   8 |     <StaticQuery
   9 |       query={graphql`{
> 10 |         ${productType} {
     |        ^^^^^^^^^^^^^^
  11 | 
  12 |         }
  13 |       }`}

File: src/components/catalog-product-card.js

There are quite a few issues I found asking for this support (#5069, #3186.) And there is good reasoning. Gatsby runs an abstract syntax tree against the components in the application Any GraphQL queries in graphql`` are extracted, executed, and passed into the component. That means there cannot be string interpolation... because there is no value to pass.

Okay, the next idea. Just use a logic check based on the productType and return a different StaticQuery component. Maybe?

      query={graphql`query($productId:String!) {
        commerceProductSimple(id:{eq:$productId }) {
          path {
      render={data => <CatalogProductCard data={data} {...props} />}

All right, so I can use a logic check to return this for a simple product type and a different one for clothing product types.

But I can't. Because this won't work either. You cannot pass variables to static queries: Static queries are really static.

­čśČBack to the drawing board. The main option is normalizing the product data into a single schema type. Currently, the gatsby-drupal-source plugin puts each product into a schema based on the product type.