✨Discover storytelling in the AI age with Pixar's Matthew Luhn at Sanity Connect, May 8th—register now

How to set the initialValue of a block field in Sanity.io

5 replies
Last updated: Sep 11, 2023
Hello đź‘‹I'm trying to pre-fill or set the
initialValue
of 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",
            },
          ],
        }),
Sep 11, 2023, 12:21 PM
You need to either explicitly add a
_key
property to any object in that array or use the
{autoGenerateArrayKeys: true}
commit config.
Sep 11, 2023, 4:02 PM
Thanks
user M
I'm using
uuid
and this works!
        defineField({
          ...
          type: "array",
          of: [{ type: "block" }],
          initialValue: [
            {
              _key: uuidv4(),
              children: [
                {
                  _key: uuidv4(),
                },
              ],
              markDefs: [],
              style: "normal",
            },
          ],
The second options could be nicer as it won't need me to set myself. The link you shared points to the write API - how would this be set on the schema
initialValue
?
Sep 11, 2023, 4:14 PM
It wouldn’t be possible in an initial value, unfortunately.
Sep 11, 2023, 4:26 PM
I see, thanks for the help anyway
user M
:gratitude-thank-you:
Sep 11, 2023, 5:29 PM
You’re welcome!
Sep 11, 2023, 5:42 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?