I’m trying to insert an item into an array in a custom input component but nothing happens.
I can see the issue! You're creating the PatchEvent but not actually calling onChange with it. PatchEvent.from() just creates the action - you need to pass it to the onChange callback that's provided to your custom input component.
Here's what your code should look like:
const handleAction = (field) => {
const patches = insert(
[{ _type: field.name }],
'after',
[-1]
)
const patchEvent = PatchEvent.from(patches).prepend(setIfMissing([]))
onChange(patchEvent) // This is the crucial part!
}Key points:
You must call
onChange- Your custom input component receives anonChangeprop from Sanity. You need to invoke it with your PatchEvent for the update to actually happen. As explained in Sanity's PatchEvent documentation,PatchEvent.from()is just an action creator - it doesn't trigger updates on its own.Use the
insert()helper - Instead of manually constructing patch objects with{ type: "insert", path: [-1] }, use theinsert()helper function. The syntax isinsert(items, position, path)where position is'before'or'after'.Chain with
prepend(setIfMissing([]))- This ensures the array field exists before trying to insert into it, which prevents errors when the field is initially undefined.Import the helpers - Make sure you're importing all the necessary functions:
import PatchEvent, { set, unset, setIfMissing, insert } from 'part:@sanity/form-builder/patch-event'Note on Studio versions: The import you're using (part:@sanity/form-builder/patch-event) is for Sanity Studio v2. If you're on Studio v3, the import path has changed to sanity and the custom input component API is different - you'd use the set() and insert() functions from the sanity package directly.
The pattern shown above follows the documented approach for array insertions in custom components, ensuring your changes properly sync with the Content Lake and work with real-time collaboration.
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.