Regression in Sanity causing custom type preview issues
Looking at your code, the issue is likely related to how initialValue works in Sanity v3 when defined on a custom type definition versus when used as a field. After the sanity upgrade, there was a change in how initial values are applied.
The problem is that when you define initialValue on a type definition (like your portals type), that initial value doesn't automatically get applied when you use that type as a field in another schema. The initialValue on a type definition only applies when that type is used directly, not when it's referenced.
Here are two solutions:
Solution 1: Move initialValue to the field (recommended)
Instead of defining initialValue on the type, define it on the field where you use it:
{
title: 'Portals',
description: 'The portals in which this API should be available in',
name: 'portals',
type: 'portals',
initialValue: ['vt', 'vtna', 'vb', 'rt', 'udt'], // Move it here
}Solution 2: Use a function for initialValue on the type
If you want to keep it on the type definition, you can use a function that returns the initial value:
export default {
name: 'portals',
type: 'array',
of: [{type: 'string'}],
initialValue: () => ['vt', 'vtna', 'vb', 'rt', 'udt'],
options: {
list: [
{title: 'Trucks', value: 'vt'},
{title: 'Trucks North America', value: 'vtna'},
{title: 'Buses', value: 'vb'},
{title: 'R Trucks', value: 'rt'},
{title: 'U Trucks', value: 'udt'},
]
},
validation: (Rule) => Rule.required(),
}Why the preview shows undefined
The portals field is showing as undefined in your preview because on existing documents, the field was never populated (since initialValue only applies to new documents). For documents created before your upgrade or before adding the initialValue, you'll need to either:
- Re-save those documents to trigger the initial value
- Add a safety check in your prepare function:
prepare({title, portals, id}) {
console.log(portals);
const subtitle = portals ? portals.join(", ").toUpperCase() : 'No portals selected'
const isDraft = id.substring(0,5) == 'draft' ? '👷' : '✅'
return {
title: title,
subtitle: subtitle,
media: <span style={{fontSize: '1rem'}}>{isDraft}</span>
}
}The preview configuration in Sanity works by selecting fields that exist on the document. If the field doesn't have a value (because it was created before the initialValue was added), it will be undefined in the prepare function, regardless of what initialValue is set to.
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.