👀 See Sanity in action: Watch product demo now →

How to get a Slug to Resolve a Reference - Cannot Read Properties Error

9 replies
Last updated: Nov 9, 2021
Hi there, I'm having trouble getting a slug to resolve a reference.
Example:

{
  name: 'person',
  title: 'Person',
  type: 'reference',
  to: [{type: 'person'}],
  validation: Rule => Rule.required(),
},
{
  name: 'code',
  title: 'Code',
  type: 'slug',
  options: {
    source: async doc => {
      // if (!doc.person) {
      //  return `${doc.person}`;
      // }
      const person = await client.getDocument(doc.person._ref)
      return `${person.family.code}`
    },
    // source: doc => `${doc.person.family.code}`,
    slugify: input => input.toUpperCase()
  },
  validation: Rule => Rule.required(),
},
Oct 23, 2021, 6:12 PM
I tried the naive approach (commented out above) but that returns a
Cannot read properties
error. I tried the suggestion at https://github.com/sanity-io/sanity/issues/1743 but got a similar error.
What is the best way to setup a slug based on a referenced field?
Oct 23, 2021, 6:14 PM
I’ve never tried something similar, but isn’t this part backwards? No idea if that is your problem here though, sorry
 if (!doc.person) {
        return `${doc.person}`;
      }

Oct 23, 2021, 6:23 PM
ahh. it seems like that code is from the issue, so I presume person is always defined in your case so that clause will never trigger
Oct 23, 2021, 6:26 PM
Yeah, the person is always defined. I think that was used in the sample to ensure it never fails?
Oct 23, 2021, 6:32 PM
I commented it out in the sample just for testing purposes to (hopefully) reduce confusion.
Oct 23, 2021, 6:33 PM
source
can’t be async I think, but
slugify
can. I think you’d need a combination of both:
source: doc => doc.person._ref,
slugify: async (personId) => {
  /* fetch etc. */
} 
Oct 25, 2021, 1:48 PM
ah, ok, i'll give this a try later
Oct 25, 2021, 4:18 PM
Took a while to get to this but wanted to let you know that this tip worked. Thanks so much for your help
user G
!
Nov 9, 2021, 6:45 AM
Took a while to get to this but wanted to let you know that this tip worked. Thanks so much for your help
user G
!
Nov 9, 2021, 6:45 AM

Sanity.io – build remarkable experiences at scale

Sanity is a customizable solution that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Categorized in