Joint session with Vercel: How to build intelligent storefronts (May 15th)

Dynamic filter for reference list based on product reference not working

13 repliesLast updated: Nov 29, 2025

Hey all! Real quick question for you. I'm trying to filter a reference list with a dynamic filter. This is where I'm currently at but it doesn't seem to do anything right now:
filter: ({ document }) => {
  const ref = document.content?.product?._ref
  if (!ref) return
  return {
    filter: 'product._ref == $product',
    params: {
      product: ref,
    },
  }
},
The document that this is being run within has a field
content.product
which references a
product
, and the document type I am trying to filter here should also reference the same
product
. You can't use
console.log
within filter functions, so I have no way to be able to inspect what
document
contains. I've tried a number of different ways of going about this, including checking for the presence of
document.content
and
document.content.product
first, but nothing seems to make a difference here.
Any ideas, anyone?
AI Update

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:

Debugging tips:

Since you can't use console.log inside the filter function, try these approaches:

If you're still having issues, it would help to know:

Show original thread
13 replies

Was this answer helpful?

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.

Related contributions