Filtering a reference list with dynamic filter in Sanity.io
Looking at your code, the issue is likely that you're trying to access nested properties that may not exist yet when the filter function runs. Here are a few things to check:
The Problem:
The document object in filter functions represents the current document being edited, so document.content?.product?._ref should work, but you need to ensure the document structure matches and that you're filtering correctly.
Solution:
Based on the Sanity documentation on reference filters, here's a corrected version:
filter: ({ document }) => {
const productRef = document?.content?.product?._ref
// Make sure we have a product reference before applying filter
if (!productRef) {
return {} // Return empty object to show all results when no product selected
}
return {
filter: 'product._ref == $productRef',
params: {
productRef: productRef,
},
}
}Key points to understand:
- Always check for existence - Your optional chaining looks good, but make sure you're checking at each level
- Return an empty object
{}when there's no filter to apply (notundefinedor nothing) - The filter applies to target documents - If you're filtering a reference field that points to some document type, the GROQ filter runs against those target documents, not your current document
- Parameter naming - I changed
producttoproductRefin params to be clearer, but the actual name doesn't matter as long as it matches in both the filter string and params object
Debugging tips:
Since you can't use console.log inside the filter function, try these approaches:
- Check your schema structure - Make sure the field path
content.productactually exists in your document - Verify the target documents - The documents you're trying to reference should also have a
productreference field that you're filtering against - Test the GROQ filter separately - Try running your GROQ query in Vision or the GROQ playground to verify it works
- Use the document inspector - In Studio, use the "Inspect" option on documents to see their actual structure
If you're still having issues, it would help to know:
- What document type has this filter?
- What document types are you referencing (the
tofield)? - Do the target documents have a
productreference field?
Sanity – Build the way you think, not the way your CMS thinks
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.