skip to Main Content

I’m building portfolio site with gastby and wordpress. If I fetch post’s features image for the site it’s working and it shows all images. But if one of my post is lacking featured image I get this error:

TypeError: Cannot read property 'localFile' of null

I found this tutorial where this guy fix that problem but I’m not getting it working for some reason.

Here in index page I’m using same logical && operator method as used in tutorial:

// src/pages/index.js
import React from "react"
import { graphql, Link } from "gatsby"
import Img from "gatsby-image"
import Layout from "../components/layout"
import SEO from "../components/seo"
const IndexPage = ({ data }) => (

  <Layout>
    <SEO
      title={data.wordpressPage.title}
      description={data.wordpressPage.excerpt}
    />
    <h1>{data.wordpressPage.title}</h1>
    <div dangerouslySetInnerHTML={{ __html: data.wordpressPage.content }} />

    {data.allWordpressPost.edges.map(edge => (
      <Link to={`/post/${edge.node.slug}`} key={edge.node.id}>
//
//
//This should handle the situation if featured image is not set
//
        {edge.node.featured_media.localFile.childImageSharp.fixed && (
          <div>
            <Img
              fixed={edge.node.featured_media.localFile.childImageSharp.fixed}
            />
          </div>
        )}


      </Link>
    ))}
  </Layout>
)
export default IndexPage
export const query = graphql`
  query {
    wordpressPage(title: { eq: "Home" }) {
      title
      excerpt
      content
    }

    allWordpressPost {
      edges {
        node {
          title
          slug
          id
          featured_media {
            localFile {
              childImageSharp {
                fixed(width: 300, height: 300) {
                  ...GatsbyImageSharpFixed
                }
              }
            }
          }
        }
      }
    }
  }
`

I’ve made same thing to BlogPost file:

// src/templates/BlogPostTemplate.js
import React from "react"
import { graphql } from "gatsby"
import Img from "gatsby-image"
import Layout from "../components/layout"
import SEO from "../components/seo"
const BlogPostTemplate = ({ data }) => (
  <Layout>
    <SEO
      title={data.wordpressPost.title}
      description={data.wordpressPost.excerpt}
    />
    <h1>{data.wordpressPost.title}</h1>
    <p>
      Written by {data.wordpressPost.author.name} on {data.wordpressPost.date}
    </p>




    {data.wordpressPost.featured_media.localFile && (
      <div>
        <Img
          fixed={
            data.wordpressPost.featured_media.localFile.childImageSharp.fixed
          }
          alt={data.wordpressPost.title}
          style={{ maxHeight: 450 }}
        />
      </div>
    )}




    <div
      style={{ marginTop: 20 }}
      dangerouslySetInnerHTML={{ __html: data.wordpressPost.content }}
    />
  </Layout>
)
export default BlogPostTemplate
export const query = graphql`
  query($id: Int!) {
    wordpressPost(wordpress_id: { eq: $id }) {
      title
      content
      excerpt
      date(formatString: "MMMM DD, YYYY")
      author {
        name
      }

      featured_media {
        localFile {
          childImageSharp {
            fixed(width: 300, height: 300) {
              ...GatsbyImageSharpFixed
            }
          }
        }
      }
    }
  }
`

Thanks in advance!

2

Answers


  1. I’ve just ran into this issue. Through a console log, I saw that featured_image was returning NULL if an image was not set.

    To compensate for the lack of an image on any given post, I wrote this as a failsafe.

    // Get the value of the featured_media response //
    const init_resolution = post.featured_media
    
    // Set resolutions to an empty string variable //
    let resolutions = ''
    
    // If init_resolution DOES NOT equal null, then set //
    // the resolutions varible to the Graphql result //
    // If init_resolution DOES equal null, then the variable 
    // will remain empty //
    
    if (init_resolution !== null) {
       resolutions = post.featured_media.localFile.childImageSharp.fixed
    }
    
    Login or Signup to reply.
  2. I know this is an old question, but I ran into the same problem and I just wanted to post the solution for whomever comes after me.

    The solution posted in the question is the correct method. Why it didn’t work for @Imlastrebor was that he should have omitted .localfile from the if statement in his examples.

    Like this:

    {data.wordpressPost.featured_media && 
        <Img fixed={data.wordpressPost.featured_media.localFile.childImageSharp.fixed} alt={data.wordpressPost.title} />
    }
    

    You can also use this method for any other fields where a user might forget to add content.

    {data.wordpressPost.content &&
    
        <p>
            {data.wordpressPost.content}
        </p>
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search