ItzaMi
ItzaMi

Reputation: 367

Optional field image and 'childImageSharp' as null | Gatsby, GraphQL & YAML

EDIT: I ended up creating a small reproduction of my problem and posted it to Gatsby's GitHub and I ended up getting some help there.
Here's the link to that issue!


I'm sorry in advance if this issue was treated somewhere else but I couldn't find an answer to what I need.

I'm currently working with Gatsby, GraphQl and YAML files and I have multiple sections that I'm mapping over but some have images and some don't.
I defined my GraphQL by stating the image with childImageSharp

sections {
              title
              description
              imageHere {
                childImageSharp {
                  fluid(maxWidth: 600) {
                    ...GatsbyImageSharpFluid_noBase64
                  }
                }
              }

and I saw a solution that involved adding this to my gatsby-node.js so that the paths could be properly read from my YAML files

exports.createSchemaCustomization = ({ actions }) => {
  const { createTypes } = actions;
  const typeDefs = `
    type allProjectPageYaml implements Node {
      imageHere: [String]!
    }
  `;
  createTypes(typeDefs);
};

Now my problem is that some sections have the imageHere field and some don't

sections:
 - title: Title 1
   description: Description 1
 - title: Title 2
   description: Description 2
   imageHere: Image1

The error I get is TypeError: Cannot read property 'childImageSharp' of null

What's my workaround this?

Upvotes: 1

Views: 3445

Answers (4)

Muhammed Moussa
Muhammed Moussa

Reputation: 5195

for me, it was a caching issue try delete .cache, public, dirs, or run

gatsby clean

UPDATE
if using netlify ci/cd, also need to add this into package.json

"resolutions": {
  "sharp": "0.24.0"
}

https://community.netlify.com/t/error-input-file-contains-unsupported-image-format-gatsby/10891/4

Upvotes: 1

Brandon LeBoeuf
Brandon LeBoeuf

Reputation: 29

Check the spelling of the filepath that ChildImageSharp is trying to reference. When I was getting this error, the img filepath needed to be corrected.

Upvotes: 1

ItzaMi
ItzaMi

Reputation: 367

I ended up creating a small reproduction of my problem and posted it to Gatsby's GitHub and I ended up getting some help there.
Here's the link to that issue!

Upvotes: 1

coreyward
coreyward

Reputation: 80041

You've defined imageHere as a required array of strings with this: imageHere: [String]!.

If it's actually supposed to be an optional image node, you might want to instead define it as the correct type (something like GatsbyImage, but I can't recall exactly what it is off-hand—you should be able to check in graphiql). That would look more like imageHere: GatsbyImage (no bang, no square brackets).

Upvotes: 0

Related Questions