Injecting a variable into a GraphQL filter query

Denizthemenace
Shopify Expert
17 1 2

I'm trying to inject a variable into a query filter:

 

query getProductsByTag($tag: String!) {
  products(query: "tag:$tag" first: 20) {
    edges {
      node {
        title
        id
      }
    }
  }
}

 

This doesn't seem to work. Getting

GraphQL error: Variable $tag is declared by getProductsByTag but not used

Is there a trick to fix this or do I need to accomplish this via String interpolation, e.g.

 

const t = "bag";
const GET_PRODUCTS_BY_TAG = gql`
  query getProductsByTag {
    products(query: "tag:${t}" first: 20) {
      edges {
        node {
          title
          id
        }
      }
    }
  }
`;

 

Asked also on stackoverflow

 

Thanks

Zin

0 Likes
_JCC_
Shopify Staff
Shopify Staff
66 10 9

Hey @Denizthemenace,

Happy to help you out with this.  The variable would have to include the field, and value being searched for. I suspect this might not be as dynamic as you're hoping for. For example,

query getProductsByTag($tagQuery: String!) {
  products(query: $tagQuery first: 20) {
    edges {
      node {
        title
        id
      }
    }
  }
}
// Query Variable
{
"tagQuery":"tag:sometag"
}

 Otherwise, string interpolation would be your best bet.

Regards,

John

John C | Developer Support @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit Shopify.dev or the Shopify Web Design and Development Blog

0 Likes