Hello everyone, can anyone tell me how to access document data from within the structure builder? ```import client from "@sanity/client" client.getDocument('tags').then(tags...
The issue you're encountering is that you're trying to import and use the Sanity client incorrectly within the Structure Builder. The getDocument method doesn't exist directly on the client import - you need to properly instantiate the client first.
Here's how to fix it:
Option 1: Create a properly configured client instance
import {createClient} from '@sanity/client'
const client = createClient({
projectId: 'your-project-id',
dataset: 'your-dataset',
useCdn: false, // Use false for fresh data in the Studio
apiVersion: '2024-01-01' // Use current date
})
client.fetch(`*[_id == "tags"][0]`).then(tags => {
console.log(tags.tagArray)
})Option 2: Use the client that's already available in Studio context
If you're working within a Structure Builder configuration file, you can access the client through the context:
import {structureTool} from 'sanity/structure'
export default {
plugins: [
structureTool({
structure: (S, context) => {
// Access client from context
const {getClient} = context
const client = getClient({apiVersion: '2024-01-01'})
// Now fetch your data
client.fetch(`*[_id == "tags"][0]`).then(tags => {
console.log(tags.tagArray)
})
return S.list()
.title('Content')
.items([...])
}
})
]
}Important notes:
- The method is
fetch()notgetDocument()- you query documents using GROQ queries - You need to properly configure the client with your
projectId,dataset, andapiVersion - When working in the Studio context, it's better to use the client from the context rather than creating a new instance
- For Structure Builder, check out the Structure Builder documentation for more examples of dynamic content loading
The createClient function is the correct way to instantiate the Sanity Client, which then gives you access to methods like fetch() for querying your content.
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.