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
Snippet 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 DocumentThis snippet will return only matched item in a sub array inside a document
Go to Sanity groq Filter by item in an arrayIt will expand the reference (projection) which is deeply linked in an array and optional using select funtion.
Go to Projection of a reference item in a deeplinked optional array.