👋 Next.js Conf 2024: Come build, party, run, and connect with us! See all events

Adding a feature flag to a Sanity type and discussing possible solutions.

7 replies
Last updated: Jul 25, 2022
Good morning everyone!
I wanted to add an
isFeatured
flag in the Sanity type.

export default {
    name: 'myType',
    type: 'object',
    title: 'My Type',
    fields: [
       ...
        {
            title: 'Is featured',
            name: 'isFeatured',
            type: 'boolean',
        },
    ],
    initialValue: {
        isFeatured: false,
    },
};
It would be marked
true
for only one object of this
myType
type. Unfortunately, here the validation itself, which will not allow to change this value to
true
when in another document this
isFeatured
flag is already on
true
, is not suitable (user-unfriendly).
I was thinking about to make a switch that - when set to
true
in obj1, would change obj2 (in which previously was `isFeatured`flag set on
true
) to
false
.
I searched the Internet for inspiration. Unfortunately, I didn't find anything that would help me. Do you have any ideas where I could start?
🤗
Jul 13, 2022, 5:53 AM
Hi!I would create a singleton document where the client can choose a featured item among all the objects.
Jul 13, 2022, 11:24 AM
{      name: 'featuredPhotos',      title: 'Featured Photos',      type: 'array',      description: 'Displayed on home page. Choose exactly 3 photos.',      of: [        {          type: 'reference',          to: [{ type: 'photo' }],        },      ],      fieldset: 'company',      options: { layout: 'grid' },      validation: (Rule) => Rule.required().min(3).max(3),    },
Jul 13, 2022, 11:25 AM
something like this:
Jul 13, 2022, 11:28 AM
{
  name: 'featuredItem',
  type: 'object',
  fields: [
    {
      title: 'Featured item',
      name: 'item',
      type: 'reference',
      to: [{type: 'item'}]
    }
  ]
}
Jul 13, 2022, 11:29 AM
Thank you for your reply! Unfortunately, I couldn't use the new page (it requires another request to Sanity, and I couldn't do that). I added an object to
myType
, which stores a
boolean
and a
datetime
. Every time someone moves the
boolean
to
true
, the current
datetime
is overwritten. On BE we will simply do a filtering of
myType
by
boolean = true
and take the object with the latest
datetime
.
Jul 15, 2022, 4:16 AM
Yes, that's also a way to solve it.
As a side note, you could have combined the query:
{
"featuredItem": *[_type == "singleton"][0] { featuredItem }
"items": *[_type == "item"]
}
Jul 15, 2022, 2:04 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?