Set initialValue for block field without manual key assignment
initialValueof a field of type
block. I get the following warning on the Studio side. Clicking "Set a new random_key.." seems to work but is there a way of this being automatically set without needing to click it?
defineField({
title: "Description",
name: "description",
type: "array",
of: [{ type: "block" }],
initialValue: [
{
_type: "block",
children: [
{
_type: "span",
marks: [],
text: "Hello there\n\nThis is a new line!",
},
],
markDefs: [],
style: "normal",
},
],
}),Yes, you're encountering the _key warning because block content in Sanity requires unique _key properties for each object in the array structure, including both the block itself and its children.
The solution is to explicitly add _key values using a UUID generator. Here's the working approach:
import {v4 as uuidv4} from 'uuid'
defineField({
title: "Description",
name: "description",
type: "array",
of: [{ type: "block" }],
initialValue: [
{
_key: uuidv4(),
_type: "block",
children: [
{
_key: uuidv4(),
_type: "span",
marks: [],
text: "Hello there\n\nThis is a new line!",
},
],
markDefs: [],
style: "normal",
},
],
})Important notes:
- You need to add
_keyto both the block object and each child span object - The
_keyvalues must be unique identifiers (UUID is perfect for this) - Unfortunately, there's no way to auto-generate these keys directly in the
initialValue- you must set them manually in your schema definition
There is an autoGenerateArrayKeys: true option in the Sanity client config, but this only applies when writing documents via the client API, not for schema-level initialValue definitions. As confirmed in the Sanity community discussion, it's not possible to use this approach with initialValue.
The manual UUID approach is the recommended solution and will eliminate the warning while ensuring your initial block content is properly structured.
Show original thread5 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.