Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 667
Undistraction Avatar asked Oct 25 '17 13:10

Undistraction


Video Answer


1 Answers

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

filter: { fields: { tags: { in: [$tag] } } }
like image 101
Undistraction Avatar answered Oct 21 '22 02:10

Undistraction