As we use Sanity.io’s GROQ more and more, we’ll soon get ourselves into situations where we will have to construct our queries dynamically. A very good example of that is say, we’re working on getting all products based on different attributes.
Imagine we have the following product filters below and their options:
In situations like this, we’ll need to write our GROQ query dynamically, that’s because only then we can formulate it when the user has done a selection. What’s more, is that the values Red, Small, and Female are dynamic too. So basically, we have two things to do:
Construct our query properly based on selected product filters
Substitute the values in
But if we use the code above when the user has filtered the products by color only then we’ll get an incorrect GROQ query, sometimes malformed:
*[color == "Red" && size == "" && gender == ""]
Not good! 😔
One last thing before we go all out! The above example is pretty contrived, GROQ queries aren’t just as simple as that. It can get more complicated especially when we’re working with all different shapes of data. In some challenging datasets, there are times that we’ll do one or many forms of projections, joins, filters, orders, pipes, and so many more.
There are tons of possibilities really and as another example, here below we added some projections to pick specific fields we want to get:
As I explored this area, there are packages you can use to simplify this task for you. Just take note though that it may not cover all use cases you might have. I’ll list them out in the Resources below. I personally just make use template literals or tagged templates and/or a combination of both.
What do you think? I’d like to hear your opinion.
GROQ tagged template literal - Used to signal that it represents a GRQO-query. The result will be the exact same string as the input - this is currently helpful for getting syntax highlighting in editors, but in the future it might also parse and validate queries, strip unncessary whitespace and similar.
minify-groq - Minifies a GROQ-query by reducing unnecessary whitespace and supports placeholder(s) just like in my example above. I would personally say that you use this.
How Queries Work - GROQ - A tutorial on using the Sanity query language GROQ. This will give you an idea how GROQ works.