Surjith S M
Web Designer & Front-end Developer. Figma, TailwindCSS & Next.js
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.
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.
Web Designer & Front-end Developer. Figma, TailwindCSS & Next.js
Suppose you have an Array Reference to Category and you want to get all posts with one of the categories listed in the current post. This is usually when you need to get related items.
Go to Get related items of a post in sanity by comparing category array reference with another arrayA short snippet to filter category, tags or other document based on total referenced count.
Go to Sanity GROQ Filter category by highest reference count in other documentsSnippet for `internalLInk` Reference in GROQ and rendering it in React/Next.js frontend using Portabletext.
Go to Sanity internalLink render in React with Portable TextSanity preview component cannot access the parent/document if its inside an array or object. Using Custom Preview component, we can solve the issue.
Go to Sanity Custom Preview Component to get Parent Document