Access current document values in custom Sanity input component
defineField({
name: "crmUpdateFieldId",
type: "string",
options: { /* snipped */ },
components: {
input: AsyncListInput,
},
}),
const AsyncListInput = (props: any) => {
const { schemaType, renderDefault } = props
const dossierTypeId = /* Get dossierTypeId from the current document somehow */
// get values from API
const values = /* snipped ... */
return renderDefault({
...props,
schemaType: { ...schemaType, options: { list: values } },
})
}AsyncListInputwe call an API and would like to supply a property value that was set in the document that is currently being edited.Is there any way to access properties from the current document from
AsyncListInput?I know we can call the Sanity API, get the draft document and take the property value that way but I'm hoping the document is already accessible in another way without doing the API call.
Yes! You can absolutely access the current document's properties in your custom input component without making an API call. The solution is to use the useFormValue hook from Sanity.
Here's how to update your AsyncListInput component:
import { useFormValue } from 'sanity'
const AsyncListInput = (props: any) => {
const { schemaType, renderDefault } = props
// Access the entire document
const document = useFormValue([])
// Or access a specific field directly
const dossierTypeId = useFormValue(['dossierTypeId'])
// get values from API using dossierTypeId
const values = /* your API call using dossierTypeId */
return renderDefault({
...props,
schemaType: { ...schemaType, options: { list: values } },
})
}The useFormValue hook takes an array path to the field you want to access:
useFormValue([])- returns the entire documentuseFormValue(['dossierTypeId'])- returns just thedossierTypeIdfielduseFormValue(['nested', 'field', 'path'])- for deeply nested fields
This is the modern, recommended approach in Sanity Studio v3. In v2, you would have used the withDocument HOC, but that's been replaced with this hook-based approach.
Important note: The component will re-render whenever the field you're watching changes. If you're watching the entire document with useFormValue([]), it will re-render on any document change. For better performance, access only the specific field(s) you need.
Show original thread4 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.