How to update another field using patch in Sanity custom component?

24 replies
Last updated: Nov 29, 2025
Hi everyone, I need a help with customComponent I am trying to change another field from the same document by
const { patch } = useDocumentOperation(props.id, props.schemaType.name);
patch.execute([{ set: { path: pathSegments, value: 'testValue' } }])
but the value of the target field is not changing, What am I missing?
AI Update

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:

  1. Use onChange from props: Your custom component receives an onChange callback in props. This is what you need to use to update field values.

  2. 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'].

  3. Why not useDocumentOperation?: The useDocumentOperation hook is designed for document actions (like custom publish buttons), not for updating fields from within custom input components. It operates at the document level, while onChange with 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 thread
24 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.

Was this answer helpful?