How to update Sanity custom input field value with PatchEvent?
Great question! I totally understand the confusion around PatchEvent - it's one of those things that clicks once you see it in action. Let me help you update your Pokemon ID field properly.
The key thing to understand is that in Sanity v3, you don't actually need to import PatchEvent anymore. You can import the patch operations (set, unset, setIfMissing) directly from 'sanity' and pass them to your onChange callback.
Here's how to update your code:
import { set, setIfMissing } from 'sanity';
// In your custom input component
export function PokemonInput(props) {
const { onChange, value = {} } = props;
async function getPokeData(pokemonName) {
const pokeApi = `https://pokeapi.co/api/v2/pokemon/${pokemonName}`;
const res = await fetch(pokeApi);
const data = await res.json();
const pokeId = data.id;
// Update the ID field in your object
onChange(set(pokeId, ['pokeId'])); // The second argument is the path
}
return (
<div>
<input
type="text"
value={value.pokemonName || ''}
onChange={(e) => {
const newName = e.target.value;
// Update the pokemonName field
onChange(set(newName, ['pokemonName']));
// Fetch the Pokemon data when name changes
if (newName) {
getPokeData(newName);
}
}}
/>
{value.pokeId && <p>Pokemon ID: {value.pokeId}</p>}
</div>
);
}Key points:
- The
onChangeprop is passed to your component and is what actually updates the document - The
set()operation takes two arguments: the value to set, and the path (as an array) to where it should be set - For object fields, use the field name as the path:
set(value, ['fieldName'])
If you want to update multiple fields at once (like both pokemonName and pokeId), you can do it in one call by setting the entire object:
onChange(set({
pokemonName: newName,
pokeId: pokeId
}));For your schema, you'd want something like:
{
name: 'pokemon',
type: 'object',
components: {
input: PokemonInput
},
fields: [
{ name: 'pokemonName', type: 'string' },
{ name: 'pokeId', type: 'number' },
{ name: 'imageUrl', type: 'string' }
]
}Once you have the ID working, you can build your image URL (https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokeId}.png) and use the Avatar component from @sanity/ui to display it!
The modern v3 approach is much simpler than the old PatchEvent pattern - just import set, unset, and setIfMissing directly from 'sanity' and pass them to onChange. The onChange callback handles all the real-time synchronization and document updates for you. You can read more about how patches work under the hood if you're curious!
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.