How to generate fresh initialValue for each new object instance in Sanity?

1 replies
Last updated: Nov 1, 2023
Hi πŸ‘‹ Is there a way to generate a fresh
initialValue
in an object being used in a pageBuilder document? I'm trying to prefill a field with a random number using initialValue but the same random number keeps appearing upon adding additional "instances" of this same object
AI Update

The issue you're experiencing is a common gotcha with initialValue in Sanity schemas. When you use initialValue: Math.random() (or any expression) directly in your schema definition, it gets evaluated once when the schema is loaded, not each time you add a new object to an array.

Here's what's happening:

// ❌ This evaluates Math.random() ONCE when schema loads
defineField({
  name: 'randomId',
  type: 'number',
  initialValue: Math.random() // Same value for all instances!
})

The solution is to use a function instead:

// βœ… This evaluates Math.random() each time a new object is created
defineField({
  name: 'randomId',
  type: 'number',
  initialValue: () => Math.random() // Fresh value each time!
})

The key difference is that when initialValue is a function, Sanity calls it each time a new instance of that object is created, generating a fresh random number.

This applies to any dynamic value you want to generate:

// Other examples of function-based initialValue
initialValue: () => new Date().toISOString()
initialValue: () => `item-${Date.now()}`
initialValue: () => crypto.randomUUID()

For more complex scenarios involving document-level templates (rather than field-level initial values), you might want to explore Initial Value Templates, which give you even more control including access to context, parameters, and async operations. But for your use case of generating random numbers in array objects, the function approach should solve your problem perfectly!

Show original thread
1 reply
just figured it out. Returning a function instead of a string does the trick. Thanks πŸ˜„

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?