✨Discover storytelling in the AI age with Pixar's Matthew Luhn at Sanity Connect, May 8th—register now

Get Sanity Reference Field Values inside Custom Schema Functions

By Surjith S M

Sanity provides various custom functions inside the schema. But getting a reference field value is difficult. Here's the how I do it using fetch.

post.js

import sanityClient from "part:@sanity/base/client";
const client = sanityClient.withConfig({ apiVersion: "2021-12-17" });

export default {
  name: 'post',
  title: 'Post',
  type: 'document',
  fields: [
    {
      name: "slug",
      title: "Slug",
      type: "slug",
      options: {
        source: (document, options) => {
          const query = '*[_type=="category" && _id == $ref]{...}';
          const params = { ref: document.category._ref };
          const cattitle = client.fetch(query, params).then(data => {
            console.log("fetched", data);
            return data[0].title;
          });
          return cattitle;
        },
        slugify: input => {
          return input
            .toLowerCase()
            .replace(/\s+/g, "-")
            .replace(/[^\w-]+/g, "");
        },
        isUnique: true
      }
    }
  ],
}

First, we call sanityClient from Sanity and configure API version. The fetch won't work without an API version.

Then in your custom function (I have used slugify as example, but it would work on all custom sanity functions) query the reference and get the data using fetch method.

Now return the data and use it as needed.

Contributor

Other schemas by author