How can I share a query between a static page and a generated one?

Viewed 65

In Gatsby, both static pages (ie. components defined in /pages) and dynamic pages (ie. "pages" created in gatsby-node.j) have a way to depend on GraphQL data by exporting a query variable. However, the static page wants a graphql-tagged string, whereas the dynamic page only wants a string:

// /pages/index.js
export const query = graphql`*QUERY*`;

vs.

// gatsby-node.js
export const query = `*QUERY*`;

If I try to use string interpolation to use the string with the tag:

export const query = graphql`${actualQuery}*`;

I get an error, because that tag doesn't allow string interpolation.

I realize that I could just keep two copies of the query: one as a plain string, and then an identical "tagged" copy ... but surely there's some way to avoid this duplication?

EDIT: Here's the relevant code:

// gatsby-node.js

export const createPages = async ({ graphql, actions: { createPage } }) => {
  // This requires a GRAPHQL *string*
  const { data } = await graphql(sharedQuery);
  data.someData.forEach((pageData) => {
    createPage({
      path: pageData.path,
      component: pathUtil.resolve('src/templates/SomePage.js'),
      context: { pageData }
    });
  });
});


// pages/index.js

// This version requires a *tagged template literal*
export const query = sharedQuery;
const IndexPage = ({ data }) => { // ... page component that uses data
export default IndexPage;
0 Answers
Related