I'm trying to fetch Shopify products on the basis of search keyword.
I tested this query by passing hard coded value in the query it works fine but I need to pass variable value so in that case it gives an error that
Grapghql query error searchKeyword is declared but not used.
Here is my query to search products on the basis of title
, tag
and product_type
.
Unsuccessful case:
export const searchProductsQuery = gql` query($searchKeyword: String!){
shop {
products(first: 10, query:"title:'$searchKeyword' OR tag:'$searchKeyword' OR product_type:'$searchKeyword'") {
edges {
cursor
node {
id
title
handle
description
productType
images(first: 5) {
edges {
node {
id
src
}
}
}
variants(first: 5) {
edges {
node {
id
title
price
}
}
}
}
}
}
}
}`;
Successful case:
export const searchProductsQuery = gql` query{
shop {
products(first: 10, query:"title:'games' OR tag:'games' OR product_type:'games'") {
...
};
The variables you define for your operation are just that -- variables. They cannot be used like a template literal placeholder, which is what you are trying to do.
In GraphQL, variables can only be used as input for an argument. For example, query
is an argument that takes a (non-null) String. So, we can create a variable like $mySearchQuery
, set it to "title:'games' OR tag:'games' OR product_type:'games'"
and then use it like this:
products(query:$mySearchQuery)
If you have a javascript variable that you want to use as part of $mySearchQuery
, you can set the value you pass in for $mySearchQuery
inside your javascript code by using a template literal:
const options = {
variables: {
mySearchQuery: `title:'${keyword}' OR tag:'${keyword}' OR product_type:'${keyword}'`
}
}
You are seeing an error that your variable was declared and never used because it never was -- the references to it inside your query are part of a string and therefore are parsed literally.