Resolving references in the structure builder for constructing a URL in Sanity.io.
11 replies
Last updated: Mar 4, 2022
K
Hi!
I'm setting up a preview iframe pane, and creating a
However, now I want to construct the URL from a referenced field. I have an
. However, the doc passed by the function (where S is the structure builder) doesn't resolve references (so
How can I resolve that doc?
I'm setting up a preview iframe pane, and creating a
resolveProductionUrlfunction, like in many of the guides suggests. I have done it before, and it works great. Usually.
However, now I want to construct the URL from a referenced field. I have an
articleschema type, that has a reference to a
categorytype. The URL is basically
${article.category.slug.current}/${article.slug.current}
S.view.options({ url: resolveProductionUrl })
article.categoryis just a regular ref object.
How can I resolve that doc?
Mar 2, 2022, 5:50 PM
K
Anyone know how to resolve references in the structure builder?
Mar 4, 2022, 7:10 AM
K
It's pretty basic
However,
export const resolveProductionUrl = (doc: any) => { const host = window.location.href.includes("localhost") ? "<http://localhost:3000>" : "<https://production.domain>"; return `${host}/${doc.category.slug?.current}/${doc.slug.current}?preview=${process.env.SANITY_PREVIEW_SECRET}`; };
doc.categoryis just an object containing a
_refto the category ID
Mar 4, 2022, 7:02 PM
Ah got it! So, set up that way, your function has no way to resolve the category reference. You'll have to import the client:
Then fetch the category values before returning the url.
import client from "part:@sanity/base/client" const sanityClient = client.withConfig({apiVersion: '2021-03-25'})
Mar 4, 2022, 11:03 PM
Ah got it! So, set up that way, your function has no way to resolve the category reference. You'll have to import the client:
Then fetch the category values before returning the url.
import client from "part:@sanity/base/client" const sanityClient = client.withConfig({apiVersion: '2021-03-25'})
Mar 4, 2022, 11:03 PM
K
Oh that’s how that’s done within the studio. Are there docs about the studio client I missed somehow?
Mar 4, 2022, 11:06 PM
K
Thanks!
Mar 4, 2022, 11:06 PM
I know it exists in the docs, but I can't remember where. I'll look around for it.
Mar 4, 2022, 11:07 PM
I know it exists in the docs, but I can't remember where. I'll look around for it.
Mar 4, 2022, 11:07 PM
K
Well, don’t spent your time doing that. I’ll find it myself. Thanks for showing me though 😍
Mar 4, 2022, 11:08 PM
K
Well, don’t spent your time doing that. I’ll find it myself. Thanks for showing me though 😍
Mar 4, 2022, 11:08 PM
Sanity– build remarkable experiences at scale
Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.