How to insert item into array using PatchEvent in custom Sanity input?

5 replies
Last updated: Nov 29, 2025
Can anyone help me here? I’m trying to insert an item into an array in a custom input component but nothing happens. I’m importing PatchEvent like this,
import PatchEvent from 'part:@sanity/form-builder/patch-event'
.And then supposedly firing in an
onAction
handler here;
const handleAction = (field) => {
    const patches = [
      { path: [], type: "setIfMissing", value: [] }, 
      {
        type: "insert",
        items: [{ _type: field.name }],
        path: [-1]
      }
    ]

    PatchEvent.from(patches)
}
But the value is never updated.
AI Update

I can see the issue! You're creating the PatchEvent but not actually calling the onChange handler to apply it. PatchEvent.from() just creates the action - it doesn't automatically update the document. You need to pass it to the onChange prop that your custom input component receives.

Here's the corrected version:

const handleAction = (field) => {
    const patches = [
      { path: [], type: "setIfMissing", value: [] }, 
      {
        type: "insert",
        items: [{ _type: field.name }],
        path: [-1]
      }
    ]

    onChange(PatchEvent.from(patches))  // ← Add this!
}

The onChange function should be passed as a prop to your custom input component from Sanity Studio. Make sure your component signature includes it:

const MyCustomInput = ({ value, onChange, type }) => {
  // your component code
}

Also, heads up: the import syntax you're using (part:@sanity/form-builder/patch-event) is from the older Sanity Studio v2. If you're on Studio v3, you'll want to update to the newer import style. Check out the PatchEvent documentation for the current approach.

For array insertions specifically, you might also want to chain setIfMissing using .prepend() to ensure the array exists before inserting:

const patches = insert([{ _type: field.name }], 'after', [-1])
const patchEvent = PatchEvent.from(patches).prepend(setIfMissing([]))
onChange(patchEvent)

This ensures you're initializing the array if it doesn't exist before trying to insert items into it.

Show original thread
5 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?