question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[gatsby-source-contentful] renderRichText fails if there is only one type of content in the schema for references

See original GitHub issue

Description

Somewhat related to #29159, as this is what made me want to type things explicitly in the first place.

Basically, if you have a RichText field where there’s only one type of entry linked in all instances of the field, the renderRichText function in gatsby-source-contentful/rich-text does not extract references correctly, which results in the entry nodes having an empty data property.

Example:

Have some contentful entry type with a single rich text field. Create a single instance of that type, and embed an Asset in it.

Using a custom nodeRender option that accesses node.data.target, e.g.

renderRichText(rtField, {
    nodeRender: {
        [BLOCKS.EMBEDDED_ASSET]: (node, children) => {
            return <Image fixed={node.data.target.fixed} />
        }
    }
})

and a graphql query like this:

query {
    allContentfulFoo {
        rtField {
            raw
            references {
                ... on ContentfulAsset {
                    fixed {
                        ...GatsbyContentfulFixed
                    }
                }
            }
        }
    }
}

You’ll get an error from the custom renderer about node.data.target being undefined.

Setting breakpoints, I can see that node.data is just an empty object. Digging a bit further, I’m seeing this when setting a breakpoint in the renderRichText function:

image

If I’m understanding this correctly, the dummyResponse object is being created by essentially partitioning the references array into entries and assets by checking the __typename field (which I believe the source plugin is supposed to add), but if you look at the right side, you can see that the references in this case does contain the fields from the query, but interestingly it _does not contain the _typename property.

This results in the dummyResponse object not containing any of the references, so the custom renderers get no data to work with.

Steps to reproduce

  1. Create Contentful space with a content type that contains a Rich Text field.
  2. Create an instance of that type, and embed an asset in the rich text field.
  3. Query for asset data from the rich text field’s references property, and pass the results into the renderRichText function (not sure if a custom renderer is required, I suspect it would render incorrectly with no error using the default rendering).

Expected result

Rich Text Asset reference data should be passed to custom renderers

Actual result

Errors when trying to access anything in the node.data object in a custom node renderer

Environment

System: OS: Windows 10 10.0.18363 CPU: (8) x64 Intel® Core™ i5-8250U CPU @ 1.60GHz Binaries: Node: 10.13.0 - C:\Program Files\nodejs\node.EXE Yarn: 1.22.0 - C:\Program Files (x86)\Yarn\bin\yarn.CMD npm: 6.4.1 - C:\Program Files\nodejs\npm.CMD Browsers: Edge: 44.18362.449.0 npmPackages: gatsby: ^2.30.1 => 2.30.1 gatsby-background-image: ^1.3.1 => 1.3.1 gatsby-image: ^2.9.0 => 2.9.0 gatsby-plugin-graphql-codegen: ^2.7.1 => 2.7.1 gatsby-plugin-manifest: ^2.10.0 => 2.10.0 gatsby-plugin-material-ui: ^2.1.10 => 2.1.10 gatsby-plugin-offline: ^3.8.0 => 3.8.0 gatsby-plugin-react-helmet: ^3.8.0 => 3.8.0 gatsby-plugin-schema-export: ^1.1.2 => 1.1.2 gatsby-plugin-sharp: ^2.12.0 => 2.12.0 gatsby-plugin-typescript: ^2.10.0 => 2.10.0 gatsby-source-contentful: ^4.4.1 => 4.4.1 gatsby-source-filesystem: ^2.9.0 => 2.9.0 gatsby-transformer-remark: ^2.14.0 => 2.14.0 gatsby-transformer-sharp: ^2.10.0 => 2.10.0

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:12

github_iconTop GitHub Comments

8reactions
trip16661commented, Apr 3, 2021

After not sleeping well I tried to trace back the information so I could see if there is something that I could do to help.

While tracking it, I ended up in the Contentful Resolve Response which handles the mapping of the response object. There I found out that the items were not being resolved because the assets were not being recognized as assets and therefore they were placed under de “Entry” category instead.

This would happen because in the dummyresponse :

  const dummyResponse = {
    items: [{
      sys: {
        type: `Entry`
      },
      richText
    }],
    includes: {
      Entry: references.filter(({
        __typename
      }) => __typename !== `ContentfulAsset`).map(reference => {
        return { ...reference,
          sys: {
            type: `Entry`,
            id: reference.contentful_id
          }
        };
      }),
      Asset: references.filter(({
        __typename
      }) => __typename === `ContentfulAsset`).map(reference => {
        return { ...reference,
          sys: {
            type: `Asset`,
            id: reference.contentful_id
          }
        };
      })
    }
  };

It will require a __typename parameter to properly separate the type being referenced…

A quick solution to this issue is to add __typename to the reference in your query:

            references {
             __typename
             ... on ContentfulAsset {
               contentful_id
               fixed(width: 1600) {
                 width
                 height
                 src
                 srcSet
               }
             }
           }

I think this was extremely confusing because it really didn’t throw any errors or anything. So you are left thinking whats wrong with your whole project rather than this particular usage.

This is all due to the lack of information in the https://www.contentful.com/developers/docs/tutorials/general/rich-text-and-gatsby/

Where they place the query without the important __typename reference…

TLDR: just add __typename to your reference in the query

1reaction
panzacodercommented, Feb 15, 2021

I a reproducing this issue with just one Entry embedded as well. I have been pulling my hair out trying to get a basic POC up for Rich Text, I would have never thought to just add more types. I’m going to try it now, 🤞

Update: this was not the solution for me. I am still just getting

{ node: { data: { } } }

for every embedded entry. Anyone else have tips here? This plugin seems totally broken to me, unless I’m doing something wrong.

PS: I’m logging out body before passing it to renderRichText and I’m seeing the data I expect in the references array.

Read more comments on GitHub >

github_iconTop Results From Across the Web

using renderRichText - receiving an error Node is not defined
All you need to do is to add references to the graphql query, unlike with json, the body has raw and references. With...
Read more >
gatsby-source-contentful
You do not need to create references on both content types. When ... Useful if you have a large space in Contentful and...
Read more >
Invalid schema error when trying to reference enum in another ...
I have created two schemas, one is just an enum that I want to reuse in different schemas, I call it ServiceEnum :...
Read more >
Graphql playground gatsby - Caritas Castellaneta
1. If you also want to try these examples out in the GraphQL Playground tool, ... This package provides support for the multipart/form-data...
Read more >
Contentful Strategies: How To Render RichText - YouTube
Creating and adjusting new fields in your content model is easy with Contentful's RichText editor. Follow along as Stefon highlights the ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found