👋 Next.js Conf 2024: Come build, party, run, and connect with us! See all events

Troubleshooting accessing data from a referenced document in GatsbyJS with Sanity schema

66 replies
Last updated: Jun 14, 2020
Hello!
I’ve put more time than I’d like to admit into figuring this one out.
😶
I’ve built a
reference schema
that I can use within my
Block Type
that pulls 1 featured document into GatsbyJS.
I’m having trouble accessing the data of the document. I am capable of pulling the 
_ref
which is equal to the
id
of the post selected so I know I’m close. How do I get pull the data and into the data of the specific document?

Schema:

export default {
  
name: 'featuredPost',
  
title: 'Featured Post',
  
type: 'object',
  
fields: [
   
{
    
title: 'post',
    
name: 'post',
    
type: 'array',
    
of: [
     
{
      
type: 'reference',
      
to: [
       
{type: 'Doc Type 1'},
       
{type: 'Doc Type 2'},
      
]
     
}
    
]
   
},
  
]
 
}


GatsbyJS:
{postId._ref}
successfully shows id of document

function SingularFeaturedPost (_props_) {

const postId = _props_.featuredPost[0]

return (

<>

<h1>Featured Post: {postId}</h1>

<p>Post Title: {postId.title}</p>

</>

)

}


export default SingularFeaturedPost;

Thanks In Advance!
Jun 10, 2020, 12:02 PM
sounds like you need to look for the
_raw
content of your blockType
can you share a GiQL of your query?
Jun 10, 2020, 1:51 PM
user N
Thanks for the response. Here’s some more information:
I’m pulling the information through the serializer of my blockContent.

Through the following GiQL query I can see the information after reference:


query MyQuery {

sanityPage {

title

_rawBlockContent(resolveReferences: {maxDepth: 10})

}

}
Jun 10, 2020, 1:58 PM
ok, so what's inside the
_rawBlockContent
? what are you serializing it to?
Jun 10, 2020, 2:00 PM
Inside the _rawBlock is:

{

"data": {

"sanityPage": {

"title": "Title",

"_rawBlockContent": [

{

"_key": "1d4f1c4d53c6",

"_type": "block",

"children": [

{

"_key": "1d4f1c4d53c60",

"_type": "span",

"marks": [

"strong"

],

"text": "Text Here"

},

{

"_key": "1d4f1c4d53c61",

"_type": "span",

"marks": [],

"text": "text here"

}

],

"markDefs": [],

"style": "normal"

},

{

"_key": "90e78fe9aa66",

"_type": "singularFeaturedPost",

"featuredPost": [

{

"_id": "06df3cdd-2aae-4b5d-bff7-2fbe7a77b65c",

"_type": "business",

"_createdAt": "2020-06-01T16:22:11Z",

"_rev": "QyhMGiXtoE71bfRC5kaum9",

"_updatedAt": "2020-06-01T21:11:52Z",

"excerpt": "Excerpt will go here. ",

"featuredContent": [

"publishedAt": "2020-04-16T05:00:00.000Z",

"slug": {

"_type": "slug",

"current": "slug-here"

},

"title": "title-here",

"id": "a6dea004-b4a8-54f9-a834-bd616ce733ec",

"parent": null,

"children": [],

"internal": {

"type": "SanityBusiness",

"contentDigest": "a81065371c02714e51e7ac1f338a10d7",

"counter": 73,

"owner": "gatsby-source-sanity"

}

}

]

},

{

"_key": "84dc53750d15",

"_type": "block",

"children": [

{

"_key": "84dc53750d150",

"_type": "span",

"marks": [],

"text": "Content:"

}

],

"markDefs": [],

"style": "normal"

},

{

"_key": "4578b407565d",

"_type": "recentPostFeed",

"contentType": "music",

"featureFirstPost": false,

"postCount": 6

},

{

"_key": "4c7e082d5de1",

"_type": "block",

"children": [

{

"_key": "4c7e082d5de10",

"_type": "span",

"marks": [],

"text": "Business:"

}

],

"markDefs": [],

"style": "normal"

},

{

"_key": "744429e46d6a",

"_type": "recentPostFeed",

"contentType": "business",

"featureFirstPost": false,

"postCount": 3

}

]

}

}

}
Jun 10, 2020, 2:07 PM
ok, so isn't that your referenced document right there? titled
title-here
??
Jun 10, 2020, 2:09 PM
Yes. Getting to it is where I’m perpetually stuck.
Jun 10, 2020, 2:10 PM
gotcha gotcha
Jun 10, 2020, 2:11 PM
props.featuredPost[0]._ref shows the ID of the doc I need information from. Getting into that doc through : props.featuredPost… is where I’m hung up.
Jun 10, 2020, 2:11 PM
ok, lets take it slow here (since i'm trying to follow code i can't test)... what do you get when you log out
props
?
Jun 10, 2020, 2:12 PM
or perhaps
props.featuredPost.title
Jun 10, 2020, 2:13 PM
I know props.featuredPost.title renders undefined
Jun 10, 2020, 2:14 PM
I’m throwing props in now.
Jun 10, 2020, 2:14 PM
mmm
Jun 10, 2020, 2:14 PM
Props Straight Up:
1. _{_key: “90e78fe9aa66”,
type: “singularFeaturedPost”, featuredPost: Array(1)}2. featuredPost: [{…}]
3. _key: “90e78fe9aa66”
4. _type: “singularFeaturedPost”
5. __proto__: Object

Jun 10, 2020, 2:15 PM
might also depend on where you're logging for
props
... before serializer and after
Jun 10, 2020, 2:15 PM
where are you logging that?
Jun 10, 2020, 2:18 PM
within my component. Right before return
Jun 10, 2020, 2:18 PM
which component? the Post component, the component that serializer sends the data to?
Jun 10, 2020, 2:20 PM
Within the singularFeaturedPost that is referenced in the serializer.
Jun 10, 2020, 2:20 PM
The one that sends the data to.
Jun 10, 2020, 2:20 PM
got it
Jun 10, 2020, 2:20 PM
so AFTER the serializer
Jun 10, 2020, 2:20 PM
Yes. Thanks for the patience.
Jun 10, 2020, 2:20 PM
which means you're not sending the right data to your component
Jun 10, 2020, 2:21 PM
so we need to go back a component and see what data you're sending through to it
Jun 10, 2020, 2:21 PM
Little more info coming…
Jun 10, 2020, 2:21 PM
ok
Jun 10, 2020, 2:21 PM
i've got to jump to a call in a few minutes but happy to continue to help till then, adn then again after
Jun 10, 2020, 2:22 PM
just as a heads up if i just stop responding for 30 min
Jun 10, 2020, 2:22 PM
I built a recent post schema type that shows 5 recent posts from any doc type selected. It works great.
With that component I’m using a staticQuery within the component that is serialized.
Jun 10, 2020, 2:22 PM
Since this is referencing one item with a defined id I’m not using a staticQuery. Is that correct?
Jun 10, 2020, 2:23 PM
Thanks for the heads up on the call.
Jun 10, 2020, 2:23 PM
yeah, you should be fine with this approach
Jun 10, 2020, 2:24 PM
i have several questions... did you query for the
_raw
somewhere? are you passing the data from that GQL query in total, all the way down to your component (through serializer)
Jun 10, 2020, 2:25 PM
that's what i'm trying to sleuth out right now
Jun 10, 2020, 2:26 PM
Here is my full seralizer.js in regards to this scenario:

import BaseBlockContent from '@sanity/block-content-to-react'

import React from 'react'

import SingularFeaturedPost from './SingularFeaturedPost'


const serializers = {

types: {

singularFeaturedPost (_props_) {

return <SingularFeaturedPost {...props.node} />

},


}

}


const BlockContent = ({ _blocks_ }) => <BaseBlockContent _blocks_={_blocks_} _serializers_={serializers} />


export default BlockContent
Jun 10, 2020, 2:30 PM
great... i'll review in a few
Jun 10, 2020, 2:30 PM
i'll be back 😉
Jun 10, 2020, 2:31 PM
Great! Thanks again.
Jun 10, 2020, 2:31 PM
Here is the page.js in full:

import React from 'react'

import { graphql } from 'gatsby'

import SiteLayout from 'c32-gatsby-theme-core/src/components/layout'

import { SEO, Layout } from "c32-gatsby-theme-core"

import GraphQLErrorList from 'c32-gatsby-theme-core/src/components/graphql-error-lists'

import Container from 'c32-gatsby-theme-core/src/components/container'

import BlockContent from '../../src/components/block-content'

`export const query = graphql``

query HomePageQuery {

page: sanityPage(_id_: {eq: "e07ca5b6-bcc6-5d90-8489-39702cd11394"}) {

title

_rawBlockContent

}

}
```


const Homepage = _props_ => {

const { data, errors } = _props_


if (errors) {

return (

<Layout>

<GraphQLErrorList _errors_={errors} />

</Layout>

)

}

const page = data && data.page

if (!page) {

throw new Error(

'Missing "Home" page data. Open the studio at <http://localhost:3333> and add "Home" page data and restart the development server.'

)

}


return (

<SiteLayout>

<Container>

<BlockContent _blocks_={ page._rawBlockContent || [] } />

</Container>

</SiteLayout>

)

}


export default Homepage
Jun 10, 2020, 2:32 PM
I’ve got a client meeting in 30min. I’ll be available until then and after that.
Jun 10, 2020, 4:09 PM
ok, so ... this looks good... i'm assuming if you log
page._rawBlockContent
you get what you're looking for on Homepage
Jun 10, 2020, 4:09 PM
For all my pages I do. I get the sanity block content.
Jun 10, 2020, 4:10 PM
And all my schema types I’ve made work as well up until this one.
Jun 10, 2020, 4:10 PM
so when are you using the
block-content-to-react
component? and when do you serialize?
Jun 10, 2020, 4:10 PM
in example, here's how one of mine is setup

import React from 'react'
import BlockContent from '@sanity/block-content-to-react'
import serializers from './Serializers'

const PortableText = ({ className, blocks }) => (
  <BlockContent className={className} blocks={blocks} serializers={serializers} />
)

export default PortableText
Jun 10, 2020, 4:11 PM
looking at your
<BlockContent>
you're not using the serializer at this step (which is where i typically have mine)
also not seeing the import of that block to react component
Jun 10, 2020, 4:12 PM
Both the block content and sericalizer are within the BlockContent
Jun 10, 2020, 4:12 PM
serializers={serializers}
Jun 10, 2020, 4:12 PM
got it
Jun 10, 2020, 4:12 PM
Oh nice catch…
Jun 10, 2020, 4:12 PM
I just noticed that the serializer isn’t at that step. One moment I’ll review.
Jun 10, 2020, 4:13 PM
just for reference to the flow i'm using.. its something like PageTemplate &gt; PortableText component &gt; Block-to-React via serializer &gt; final component
Jun 10, 2020, 4:16 PM
I’m going to move my serializer down to the initial level and try your order. It’ll take a while with work requirements. Ideally I’ll report back that it was a success.
I see your in the MPLS area as well. Small world.
🙌
Jun 10, 2020, 4:24 PM
sounds good... let me know when you get there... i'm happy to share files for any of this if its helpful
Jun 10, 2020, 4:28 PM
where in MPLS are you?
Jun 10, 2020, 4:30 PM
AV, You?
Jun 10, 2020, 5:14 PM
SLP
Jun 10, 2020, 5:16 PM
was just thinking abotu this more.... i think you need the serializer at the same point as the block-to-react component, as i think it needs the serializer
Jun 10, 2020, 5:17 PM
Jun 10, 2020, 5:19 PM
i think serializer and block-to-react go hand in hand
Jun 10, 2020, 5:19 PM
Gave restructuring it a shot so it looked identical to your approach. I had same inability to get information from within the referenced document types.
If I log
const featuredPost = _props_.featuredPost[0]._type
it returns
reference
. This seems one level up. I would assume the array is contained within the type
reference
rather than
reference
being in the first spot of the array.
I think this is the foundation of my user error. I SUPER appreciate the help today.
Jun 10, 2020, 8:39 PM
user M
Let me know if you need any additional information. Thanks for looking into this!
Jun 11, 2020, 7:36 PM
interesting... i'll be interested to hear what
user M
has to say
Jun 11, 2020, 7:40 PM
user M
responded with the solution:
Your 
/pages/index.js
 file, where you query 
_rawBlockContent
, try querying it with 
resolveReferences
. For example:
export const query = graphql`
  query HomePageQuery {
    page: sanityPage(id: {eq: "e07ca5b6-bcc6-5d90-8489-39702cd11394"}) {
      title
      _rawBlockContent(resolveReferences: {maxDepth: 5})
    }
  }
`
Good to know the scope starts shallow and can show more depth by request. Makes sense.
Jun 14, 2020, 12:07 AM
Thanks for re-posting the solution here, Ryan! And thanks for all the troubleshooting you both did on the way, really appreciated. cc: Bryce 🙂
Jun 14, 2020, 9:25 AM

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.

Was this answer helpful?