How to update another field using patch in Sanity custom component?
const { patch } = useDocumentOperation(props.id, props.schemaType.name);
patch.execute([{ set: { path: pathSegments, value: 'testValue' } }])I see your issue! When working in a custom component, you shouldn't use useDocumentOperation to update other fields in the same document. Instead, you need to use PatchEvent with the onChange callback that's passed to your custom component via props.
Here's the correct approach:
import { set, unset } from 'sanity'
// In your custom component
function MyCustomComponent(props) {
const { onChange } = props
const updateAnotherField = (value) => {
// Create a patch event targeting the field you want to update
onChange(set(value, ['fieldName']))
}
return (
<button onClick={() => updateAnotherField('testValue')}>
Update Field
</button>
)
}Key points:
Use
onChangefrom props: Your custom component receives anonChangecallback in props. This is what you need to use to update field values.Path specification: The second argument to
set()is the path as an array. For a top-level field, it's just['fieldName']. For nested fields, it would be['parent', 'child', 'fieldName'].Why not
useDocumentOperation?: TheuseDocumentOperationhook is designed for document actions (like custom publish buttons), not for updating fields from within custom input components. It operates at the document level, whileonChangewith PatchEvent is the proper way to handle field-level updates.
For more complex updates:
If you need to update multiple fields or work with objects:
import { set, setIfMissing } from 'sanity'
// Update a simple field
onChange(set('testValue', ['targetField']))
// Update a nested field in an object
onChange(set('testValue', ['parentObject', 'childField']))
// Ensure field exists before setting
onChange([setIfMissing({}), set('testValue', ['targetField'])])This approach ensures your changes work properly with Sanity's real-time collaboration features and form state management.
Show original thread24 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.