Search code examples
graphqlgatsbygatsby-imagesanity

Querying images from Sanity for GatsbyImage


I'm having trouble sourcing images from Sanity using the new gatsby-plugin-image. The documentation says to do the following:

import React from 'react'
import {getGatsbyImageData} from 'gatsby-source-sanity'
import {GatsbyImage} from 'gatsby-plugin-image'

const Person = ({data}) => {
  const imageData = getGatsbyImageData(data.sanityPerson.profileImage.asset)
  
  return <GatsbyImage image={imageData}/>
}

export default Person

export const query = graphql`
  query PersonQuery {
    sanityPerson {
      profileImage {
        asset
      }
    }
  }
`

However when I try and query the image asset, I get the following error: GraphQL error message

My query looks like this:

export const query = graphql`
  query MyQuery {
    allSanityAbout {
      nodes {
        about_text
        about_image {
          alt
          image {
            asset
          }
        }
      }
    }
  }
`;

The docs also say that "Any GraphQL File object that includes an image will have a childImageSharp field" but I can't work out how to query for it: enter image description here

Here are the fields available inside the image node: enter image description here

I get errors telling me Cannot query field "childImageSharp" on fields SanityImage or SanityImageAsset if I try and query for childImageSharp on the image or asset nodes.

Any pointers greatly appreciated!


Solution

  • Things changed a bit in the recent version of both Gatsby and Sanity. In their example, you can see that their getGatsbyImageData function is using the asset object directly object as parameter (and not using -> image -> asset like in the gatsby docs you are refering to). There is no use for fluid or fixed in the GastbyImage in Gatsby V3. In your case, you could try querying like this:

    export const query = graphql`
      query MyQuery {
        allSanityAbout {
          nodes {
            about_text
            about_image {
              asset
              alt
            }
          }
        }
      }
    `;
    

    Sending the return asset object to the sanity method getGatsbyImageData should work. Note how this method is getting the image parameter for you to use in GatsbyImage

    ...
      const imageData = getGatsbyImageData(data.sanityPerson.profileImage.asset)
      return <GatsbyImage image={imageData}/>
    ...