
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeThe 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!
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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store