BloodOverdrive
BloodOverdrive

Reputation: 378

Gatsby - Cannot read property 'childImageSharp' of null

I'm getting this error even my query giving me a proper results in GraphQL Explorer.

I'm trying to load cover images for articles, but I can't see where is error.

There is a lot blog posts and same questions, but I didn't found right answer which would fix this error.

Error: TypeError: Cannot read property 'childImageSharp' of null

This is what I've tried so far:

Mdx


    ---
    title: Hello World - from mdx!
    date: 2019-06-01
    published: true
    tags: ['react', 'javascript']
    ---

Gatsby Component

const Blog = ({ data }) => {
  const tags = data.allMdx.group
  const posts = data.allMdx.nodes

  return (
    <Layout>
      <div className="hero blog-section">
        <div className="hero-body">
          <div className="container">
            <h1 className="home-title is-size-1">Blog</h1>
            <h3 className="home-subtitle is-size-4">
              Thoughts about programming, design and random stuff
            </h3>
            <div className="tags"></div>
            <div class="tags">
              {tags.map(tag => (
                <Link
                  to={`/tags/${kebabCase(tag.fieldValue)}/`}
                  className="tag is light"
                >
                  {tag.fieldValue}
                </Link>
              ))}
            </div>

            {posts.map(({ id, excerpt, frontmatter, fields }) => (
              <Link to={fields.slug}>
                <div key={id} className="card is-fullimage mb-1">
                  <Img fluid={frontmatter.cover.childImageSharp.fluid} />
                  <div className="card-stacked">
                    <div className="card-content">
                      <time className="home-red">{frontmatter.date}</time>

                      <h1 className="is-size-4">{frontmatter.title}</h1>
                      <p>{excerpt}</p>
                      <span className="home-red">
                        {fields.readingTime.text}
                      </span>
                    </div>
                  </div>
                </div>
              </Link>
            ))}
          </div>
        </div>
      </div>
    </Layout>
  )
}

Query

export const query = graphql`
  query SITE_INDEX_QUERY {
    allMdx(
      sort: { fields: [frontmatter___date], order: DESC }
      filter: { frontmatter: { published: { eq: true } } }
    ) {
      group(field: frontmatter___tags) {
        fieldValue
      }
      nodes {
        id
        excerpt(pruneLength: 100)
        frontmatter {
          tags
          title
          date(formatString: "MM/DD/YYYY")
          cover {
            publicURL
            childImageSharp {
              fluid(maxWidth: 2000, traceSVG: { color: "#639" }) {
                tracedSVG
              }
            }
          }
        }
        fields {
          slug
          readingTime {
            text
          }
        }
      }
    }
  }
`

gatsby-config.js

module.exports = {
  siteMetadata: {
    title: `Lorem Ipsum Blog`,
    description: `Lorem ipsum.`,
  },
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/src/images`,
        name: `images`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/posts`,
        name: `posts`,
      },
    },
    {
      resolve: `gatsby-plugin-mdx`,
      options: {
        extensions: [`.mdx`, `.md`],
      },
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          {
            resolve: `gatsby-remark-images`,
            options: {
              maxWidth: 630,
            },
          },
        ],
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    `gatsby-plugin-sass`,
    `gatsby-plugin-dark-mode`,
    `gatsby-plugin-feed`,
    `gatsby-remark-reading-time`,
  ],
}

Thanks in advance

Upvotes: 2

Views: 1286

Answers (2)

Ferran Buireu
Ferran Buireu

Reputation: 29320

According to your MDX:

---
title: Hello World - from mdx!
date: 2019-06-01
published: true
tags: ['react', 'javascript']
---

You don't have cover image in all posts, so at the moment you are requesting for frontmatter.cover.childImageSharp.fluid your code is breaking. Add a simple condition at:

  const tags = data.allMdx.group
  const posts = data.allMdx.nodes

  return (
    <Layout>
      <div className="hero blog-section">
        <div className="hero-body">
          <div className="container">
            <h1 className="home-title is-size-1">Blog</h1>
            <h3 className="home-subtitle is-size-4">
              Thoughts about programming, design and random stuff
            </h3>
            <div className="tags"></div>
            <div class="tags">
              {tags.map(tag => (
                <Link
                  to={`/tags/${kebabCase(tag.fieldValue)}/`}
                  className="tag is light"
                >
                  {tag.fieldValue}
                </Link>
              ))}
            </div>

            {posts.map(({ id, excerpt, frontmatter, fields }) => (
              <Link to={fields.slug}>
                <div key={id} className="card is-fullimage mb-1">
                  {frontmatter.cover && <Img fluid={frontmatter.cover.childImageSharp.fluid} /> } 
                  <div className="card-stacked">
                    <div className="card-content">
                      <time className="home-red">{frontmatter.date}</time>

                      <h1 className="is-size-4">{frontmatter.title}</h1>
                      <p>{excerpt}</p>
                      <span className="home-red">
                        {fields.readingTime.text}
                      </span>
                    </div>
                  </div>
                </div>
              </Link>
            ))}
          </div>
        </div>
      </div>
    </Layout>
  )
}

Basically, if the looped post doesn't come with frontmatter.cover, don't print the image.

  {frontmatter.cover && <Img fluid={frontmatter.cover.childImageSharp.fluid} /> }

If you've added the Babel plugin for optional chaining from new ECMAScript you can simplify it by:

 <Img fluid={frontmatter?.cover?.childImageSharp?.fluid} />

Keep in mind cleaning cache with gatsby clean in the meantime.

Upvotes: 3

BloodOverdrive
BloodOverdrive

Reputation: 378

Strange answer but with gatsby clean I've managed to solve this issue.

Upvotes: 1

Related Questions