How to dynamically create a structure for a desk in Sanity?

456 Views Asked by At

Experimenting with Sanity Studio and looking to create a desk with a defined schema based on a referenced array of objects that would be stored in an external file. Given the sample array of objects for days:

const days = [
  {
    id: '0',
    title: 'Monday',
    schemaType: 'mon',
    icon: '',
  },
  {
    id: '4',
    title: 'Thursday',
    schemaType: 'thurs',
    icon: '',
  },
  {
    id: '5',
    title: 'Friday',
    schemaType: 'fri',
    icon: '',
  },
]

if I try to build a structure dynamically with:

export default defineStructure<ListItemBuilder>((S, context) => {
  console.log('context', context)
  return days.map(d => S.listItem().title(d.title).icon(d.icon).schemaType(d.schemaType))
})

I get an error of:

List items must be of type "listItem", got "array" - did you forget to spread (...moreItems)?

reference, but per the docs on Lists and the example with the listItem method:

export const structure = (S) =>
  S.list()
    .title('Content')
    .items([
      S.listItem()
        .title('Future projects')
        .schemaType('sampleProject')
        .child(
          S.documentList()
            .title('Future projects')
            .filter('_type == "sampleProject" && publishedAt > now()')
        )
      ])

it should be working. Given the hard coded mon works:

export default defineStructure<ListItemBuilder>((S, context) => {
  console.log('context', context)
  return S.listItem().title('Dummy').schemaType('mon')
})

entire file:

import {ListItemBuilder} from 'sanity/structure'
import defineStructure from '../utils/defineStructure'

const days = [
  {
    id: '0',
    title: 'Monday',
    schemaType: 'mon',
    icon: '',
  },
  {
    id: '4',
    title: 'Thursday',
    schemaType: 'thurs',
    icon: '',
  },
  {
    id: '5',
    title: 'Friday',
    schemaType: 'fri',
    icon: '',
  },
]

export default defineStructure<ListItemBuilder>((S, context) => {
  console.log('context', context)
  return days.map(d => S.listItem().title(d.title).icon(d.icon).schemaType(d.schemaType))
})

defineStructure.ts:

import {ConfigContext} from 'sanity'
import {StructureBuilder} from 'sanity/structure'

export default function defineStructure<StructureType>(
  factory: (S: StructureBuilder, context: ConfigContext) => StructureType,
) {
  return factory
}

sanity.config.ts (stripped):

import {defineConfig} from 'sanity'

// Plugins
import {structureTool} from 'sanity/structure'
import {structure} from './desk'


export default defineConfig({
  plugins: [structureTool({structure})],
})

In Sanity how can I dynamically create a desk based on an array of objects?

0

There are 0 best solutions below