Can the results of a query in documentList be reused inside the function?
3 replies
Last updated: Sep 19, 2020
AI Update
Looking at the Structure Builder API, yes - you can query for the count and use it in your document list title! The context parameter passed to your structure function includes a getClient method that returns a configured Sanity client.
Here's how to make your title dynamic with the query count:
// sanity.config.js
import {structureTool} from 'sanity/structure'
export default defineConfig({
// ... other config
plugins: [
structureTool({
structure: async (S, context) => {
// Get a configured Sanity client from context
const client = context.getClient({apiVersion: '2023-01-01'})
// Fetch the count
const count = await client.fetch(
'count(*[_type == "property" && count(inspectionTimes) > 0])'
)
return S.list()
.title('Content')
.items([
S.documentList()
.schemaType('property')
.title(`${count} Properties with Inspection Times`)
.filter('_type == "property" && count(inspectionTimes) > 0')
])
}
})
]
})The key points from the Structure Builder API Reference:
- The
contextparameter includes several useful properties, includinggetClient- a callback function that returns a configured SanityClient - Your structure function can be async - this allows you to
awaitquery results before building your structure - Use
context.getClient()to get a client instance, optionally passing configuration like an API version
You can also make this more reusable with a list item:
structure: async (S, context) => {
const client = context.getClient({apiVersion: '2023-01-01'})
const propertiesWithInspections = await client.fetch(
'count(*[_type == "property" && count(inspectionTimes) > 0])'
)
return S.list()
.title('Content')
.items([
S.listItem()
.title(`${propertiesWithInspections} Properties with Inspection Times`)
.child(
S.documentList()
.title(`${propertiesWithInspections} Properties with Inspection Times`)
.schemaType('property')
.filter('_type == "property" && count(inspectionTimes) > 0')
),
// ... other items
])
}Important notes:
- Remember to specify an
apiVersionwhen callinggetClient()for consistent behavior - The structure function runs when you load the Studio, but the count won't update in real-time as documents change - you'll need to refresh the Studio to see updated counts
- If you're using this pattern in multiple places, consider extracting it into a helper function to keep your structure definition clean
Show original thread3 replies
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.