
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeYes, you can make that filter conditional! The select() function in GROQ is perfect for this. It works like a switch statement and lets you conditionally apply filters based on whether a parameter is defined.
Here's how to update your query:
const getPostsQuery = groq`
*[
_type == "post"
&& select(
defined($categoryId) => $categoryId in categories[]._ref,
true
)
] | order(publishedDate desc) {
title,
slug {
current
},
publishedDate,
shortDescription,
cardImage {
...,
asset-> {
...,
}
}
}[$start...$end]
`The key change is using select() with defined():
$categoryId is defined (not null), it applies the filter $categoryId in categories[]._ref$categoryId is not defined, it returns true, which means the filter passes for all documentsThis way, when you pass in an _id, it filters by category. When you don't pass anything (or pass undefined), it returns all posts without applying the category filter.
The select() function evaluates conditions in order and returns the value of the first condition that's true, making it ideal for conditional parameter filtering like this.
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store