How to generate a document with code with an custom inputComponent?
Yes, absolutely! You can create documents programmatically from within a custom input component. Here's how to do it:
Using useClient Hook
The key is to use the useClient hook to get a Sanity client instance, then call its create() method:
import { useClient } from 'sanity'
import { set, unset } from 'sanity'
export function MyCustomInput(props) {
const { onChange } = props
const client = useClient({ apiVersion: '2023-01-01' })
const handleCreateDocument = async () => {
try {
const newDoc = await client.create({
_type: 'myDocumentType',
title: 'New Document',
// ... other fields
})
console.log('Created document:', newDoc)
// Optionally update the current field value
onChange(set(newDoc._id))
} catch (error) {
console.error('Error creating document:', error)
}
}
return (
<button onClick={handleCreateDocument}>
Create New Document
</button>
)
}Important Points
- API Version: Always specify an
apiVersionwhen usinguseClient - Async Operations: Document creation is asynchronous, so use
async/await - Updating Form State: Use the
onChangeprop with PatchEvent operations (set(),unset()) to update the current field if needed - Error Handling: Always wrap in try/catch for better error handling
Setting Up the Custom Input Component
To use your custom input component, add it to your schema field definition:
{
name: 'myField',
type: 'string',
components: {
input: MyCustomInput
}
}Common Use Cases
- Creating referenced documents on-the-fly
- Generating related content automatically
- Building wizard-like interfaces that create multiple documents
- Creating child documents from parent forms
The useClient hook gives you full access to the Sanity client API, so you can also update, delete, patch, or query documents as needed within your custom input component. Check out the custom input components guide for more patterns and best practices!
Show original thread5 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.