Undistraction
Undistraction

Reputation: 43351

Passing variable into regex In Gatsby graphql query

I have the following query which is receiving the variable $tag. Currently I am filtering the results based on the value of its frontmatter.keywords. keywords is a comma separated string, so I need to use a regex to check for the inclusion of $tag within it, however I can't work out how to pass the variable into the regex. If I hardcode a value into the regex (as in the code below where I have hardcoded /example/, the filtering works. If I replace example with $tag I receive an Error:

GraphQLError: Variable "$tag" is never used in operation "TagQuery".

export const pageQuery = graphql`
  query TagQuery($tag: String) {
    allMarkdownRemark(
      limit: 100
      sort: { fields: [frontmatter___date], order: DESC }
      filter: { frontmatter: { keywords: { regex: "/example/" } } }
    ) {
      totalCount
      edges {
        node {
          fields {
            slug
          }
          excerpt
          frontmatter {
            title
            keywords
            date
          }
        }
      }
    }
  }
`;

How should I use $tag within the regex?

I'd actually prefer to take a different approach and add the tags as an array in gatsby-node.js, but there doesn't appear to be any way of filtering based on the value of the array.

Upvotes: 12

Views: 4924

Answers (2)

obh
obh

Reputation: 334

Wherever you are passing $tag, just transform it to

const $tag = "\/".concat(tag).concat("\/")

But your error is specifically pointing to the fact that your query is not using the variable at all. So you'd also need to do

filter: { frontmatter: { keywords: { regex: $tag } } }

Upvotes: 0

Undistraction
Undistraction

Reputation: 43351

I ended up splitting the tags into an array, then using the following to filter:

filter: { fields: { tags: { in: [$tag] } } }

Upvotes: 4

Related Questions