Display random document in the studio desk

By Henrique Doro

Use an asynchronous list item in the structure builder to display a random document


import S from '@sanity/desk-tool/structure-builder'
import client from 'part:@sanity/base/client'

export default () =>
      // New item in the desk menu:
        // Add a recognizable title & icon
        .title('Random idea')
        // And use an async function to resolve its content
        .child(async () => {
          // It'll first fetch the ids of every idea in the dataset
          const ids = await client.fetch(`*[_type == 'idea']._id`)
          // Get a random one from that list
          const chosenId = getRandomItem(ids)
          // And display the document for this random one
          return S.document().id(chosenId).schemaType('idea')
      // ...
// Used to find a random id every time the
// "Random Idea" menu is clicked
function getRandomItem(arr) {
  const randomIndex = Math.floor(Math.random() * arr.length)
  return arr[randomIndex]

This is a prime example of how you can achieve bespoke and effective UIs for your editors with Sanity's structure builder.

Notice how we have an async function as the child of the "Random Idea" list item: this allows us to fetch the _id of every idea from Sanity's API, then pick a random one and display a document view for that (S.document().id(chosenId)).

I've also recorded a video going through it and wrote about it a bit more in-depth in my blog, in case something is unclear or you want to dive deeper :)