How to generate a document with code with an custom inputComponent?

5 replies
Last updated: Sep 24, 2020
Hello! i am trying to generate a document with code with an custom inputComponent, is it possible? can anyone guide me a little?
AI Update

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

  1. API Version: Always specify an apiVersion when using useClient
  2. Async Operations: Document creation is asynchronous, so use async/await
  3. Updating Form State: Use the onChange prop with PatchEvent operations (set(), unset()) to update the current field if needed
  4. 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 thread
5 replies
You can use the sanity client to create one
import client from 'part:@sanity/base/client'

client.create({_type: 'whatever', yourfields... })
wow πŸ˜„ thanks a lot, will give it a try right now!
let me know if it works or not, I typed it from memory so could be a different method name or something πŸ˜…
Of course! now i know where i can take a look at) will come back here and let you know
user G
Got it working! your code by memory was perfect πŸ˜„ so happy with this

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.

Was this answer helpful?