Boolean field initialValue set to true displays toggle in middle position

6 replies
Last updated: Jun 17, 2021
Hi! πŸ™‚ I have a question about Boolean types.So I've created a
boolean
initialValue
to true but when I try to run locally sanity studio the toggle is in the middle πŸ€”
Am I missing something out? Sorry but I'm new to the platform
πŸ™‚
AI Update

No worries, this is a common confusion when starting with Sanity! The "toggle in the middle" state you're seeing is actually the undefined state for a boolean field. This happens because initialValue only applies when a document is first created from a template, but if you're viewing an existing document or the field hasn't been set yet, it shows as undefined (middle position).

Here are a few solutions:

1. Field-level initialValue (simplest for new documents)

In your schema definition, you can set the initialValue directly on the field:

defineField({
  name: 'approved',
  type: 'boolean',
  initialValue: true
})

This will set the value to true when new documents are created, but won't affect existing documents that already have an undefined value[^1].

2. Handle undefined in your application

In your queries or application code, you can treat undefined as false (or true, depending on your needs):

const isApproved = document.approved ?? true // defaults to true if undefined

3. Update existing documents

If you have existing documents with undefined boolean values, you'll need to update them. You can do this through the Studio UI by toggling each field, or use a migration script to bulk update documents.

4. Make the field required

If you want to force a value to be set:

defineField({
  name: 'approved',
  type: 'boolean',
  initialValue: true,
  validation: Rule => Rule.required()
})

The key thing to remember is that boolean fields in Sanity have three states: true, false, and undefined (the middle toggle position). The initialValue property only applies to newly created documents, not existing ones.

Hope this helps! Let me know if you need clarification on any of these approaches πŸ™‚

Show original thread
6 replies
I've added in the
fields
array a new boolean type and run the studio
its for an existing one πŸ™‚
Initial values will only work for new documents, so anything already created would need to be set manually. However, any new documents should respect your
initialValue
setting.
If you have hundreds or more documents to set, you could also set them programmatically.
Sweet, I get it!! Thanks for the help
user A
appreciate it πŸ™‚
Great! πŸ™Œ

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?