String interpolation is not allowed in graphql tag. (Gatsby)

Viewed 4868

Attempting to use an alias for a long complicated Ids within my graphql query:

FAILED TO COMPILE: String interpolation is not allowed in graphql tag:

const query = graphql`
  query MyQuery {
    wordpress {
      menu(id: "${wordpress("mainMenu")}") {
        ...rest of query
      }
    }
  }
`
1 Answers

You should use query variable instead.

Variables can be added to page queries (but not static queries) through the context object that is an argument of the createPage API. docs

// inside template file
export const query = graphql`
  query MyQuery($id: String!) {
    menu(id: { eq: $id }) {
        ...rest of query
    }
  }
`

Then you can provide such variable as part of the page’s context in gatsby-node.js. For example:

// gatsby-node.js
const postTemplate = path.resolve(`./src/templates/post.js`)
allWordpressPost.edges.forEach(edge => {
  createPage({
    path: `/${edge.node.slug}/`,
    component: slash(postTemplate),
    context: {
      id: edge.node.id, // 
    },
  })
})

Have a look at this using-wordpress example from gatsby.

Related