GatsbyImage - GraphQL TypeError: Cannot Read Property 'Split' of Undefined

12 replies
Last updated: Mar 25, 2021
How do you get GatsbyImage to work with gatsby-sanity-source?I have implemented this (
https://github.com/sanity-io/gatsby-source-sanity#using-images ) exactly as shown in the example, but cannot get it to work as shown.I have formatted my query exactly as shown (notice just the “asset”, without the “fluid, src, or gatsbyImage:

query vehicleQuery($slug: String) {
  sanityVehicle(id: {eq: $slug}) {
    id
    _id
    modellbetegnelse
    manufacturer {
      label
      logoimage {
        asset 
      }
    }
However, this gives me an error on build:

GraphQLError: Field "asset" of type "SanityImageAsset" must have a selection of subfields. Did you mean "asset { ... }"?


If I add fluid, src, and even gatsbyImageData to the query:

query vehicleQuery($slug: String) {
  sanityVehicle(id: {eq: $slug}) {
    id
    _id
    modellbetegnelse
    manufacturer {
      label
      logoimage {
        asset {
          fluid {
            src
          }
          gatsbyImageData
        }
      }
    }
I get a different error:

WebpackError: TypeError: Cannot read property 'split' of undefined


failed Building static HTML for pages - 0.243s

 ERROR #95313 

Building static HTML failed for path "/vehicles/-d9d34e74-0ffb-5ae8-b103-7895bfbd02c7"

See our docs page for more info on this error: <https://gatsby.dev/debug-html>

  161 |     var hasOriginalRatio = desiredAspectRatio === dimensions.aspectRatio;
  162 |     var outputHeight = Math.round(height ? height : width / desiredAspectRatio);
> 163 |     var imgUrl = isOriginalSize(width, outputHeight) ||
      |                                                 ^
  164 |         (hasOriginalRatio && width > dimensions.width && outputHeight > dimensions.height)
  165 |         ? url
  166 |         : url + "?w=" + width + "&h=" + outputHeight + "&fit=crop";


  WebpackError: TypeError: Cannot read property 'split' of undefined
  
  - getGatsbyImageProps.ts:163 
    gatsby-starter-hello-world/src/images/getGatsbyImageProps.ts:163:49
  
  - getGatsbyImageProps.ts:393 
    gatsby-starter-hello-world/src/images/getGatsbyImageProps.ts:393:21
  
  - vehicledetail.js:14 
    gatsby-starter-hello-world/src/templates/vehicledetail.js:14:36
  
  - extends.js:8 
    [gatsby-starter-hello-world]/[@babel]/runtime/helpers/extends.js:8:1
  
  - extends.js:14 
    [gatsby-starter-hello-world]/[@babel]/runtime/helpers/extends.js:14:1
  
  - extends.js:13 
    [gatsby-starter-hello-world]/[@babel]/runtime/helpers/extends.js:13:1
  
  - static-entry.js:263 
    gatsby-starter-hello-world/.cache/static-entry.js:263:20
  
  - history.js:26 
    [gatsby-starter-hello-world]/[@gatsbyjs]/reach-router/es/lib/history.js:26:1
A bit lost here… if I skip GatsbyImage altogether, and just use fluid src with &lt;img src.., the site builds fine, including showing images.


System:
    OS: macOS 11.2.3
    CPU: (8) x64 Intel(R) Core(TM) i7-7920HQ CPU @ 3.10GHz
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 15.12.0 - /usr/local/bin/node
    npm: 7.6.3 - /usr/local/bin/npm
  Languages:
    Python: 2.7.16 - /usr/bin/python
  Browsers:
    Chrome: 89.0.4389.90
    Firefox: 86.0
    Safari: 14.0.3
  npmPackages:
    gatsby: ^3.0.1 => 3.1.2
    gatsby-plugin-image: ^1.1.1 => 1.1.2
    gatsby-plugin-postcss: ^4.1.0 => 4.1.0
    gatsby-plugin-sharp: ^3.1.1 => 3.1.2
    gatsby-source-filesystem: ^3.1.0 => 3.1.0
    gatsby-source-sanity: ^7.0.0 => 7.0.0
    gatsby-transformer-sharp: ^3.1.0 => 3.1.0
  npmGlobalPackages:
    gatsby-cli: 3.1.0
any ideas?
AI Update

I can see you're experiencing issues with gatsby-plugin-image and gatsby-source-sanity integration in Gatsby v3. The error you're getting is related to how you need to query images with the new plugin. Let me explain what's happening and how to fix it.

The problem is that Gatsby v3 introduced gatsby-plugin-image which replaced the old gatsby-image plugin, and the way you query images has changed significantly. You should not be querying fluid or src anymore - those were part of the old API.

The Solution

1. Update your GraphQL query to use gatsbyImageData:

query vehicleQuery($slug: String) {
  sanityVehicle(id: {eq: $slug}) {
    id
    _id
    modellbetegnelse
    manufacturer {
      label
      logoimage {
        asset {
          gatsbyImageData(
            width: 400
            placeholder: BLURRED
            formats: [AUTO, WEBP]
          )
        }
      }
    }
  }
}

2. Use the GatsbyImage component correctly in your template:

import { GatsbyImage, getImage } from "gatsby-plugin-image"

// In your component:
const VehicleDetail = ({ data }) => {
  const image = getImage(data.sanityVehicle.manufacturer.logoimage.asset)
  
  return (
    <div>
      {image && (
        <GatsbyImage 
          image={image} 
          alt={data.sanityVehicle.manufacturer.label || "Logo"} 
        />
      )}
    </div>
  )
}

export default VehicleDetail

Why You're Getting the Errors

  1. "Field 'asset' must have a selection of subfields" - This happens because GraphQL requires you to specify what data you want from the asset object. You can't just query asset by itself.

  2. "Cannot read property 'split' of undefined" - This error occurs because when you tried to query fluid and src, those fields don't exist in the new gatsby-plugin-image API, so the data structure being passed to getGatsbyImageProps is malformed.

Important Notes

  • With gatsby-source-sanity, you should be using gatsbyImageData (not fluid or fixed)
  • The getImage() helper function from gatsby-plugin-image safely extracts the image data
  • Always add a null check ({image && ...}) before rendering GatsbyImage to prevent errors if the image is missing
  • Make sure both gatsby-plugin-image AND gatsby-plugin-sharp are installed and configured in your gatsby-config.js

Verify Your Setup

Make sure your gatsby-config.js includes both plugins:

module.exports = {
  plugins: [
    {
      resolve: 'gatsby-source-sanity',
      options: {
        projectId: 'your-project-id',
        dataset: 'your-dataset',
        // ... other options
      },
    },
    'gatsby-plugin-image',
    'gatsby-plugin-sharp',
  ],
}

The fact that using fluid.src with a regular <img> tag works confirms your Sanity images are properly configured - you just need to use the correct modern API for gatsby-plugin-image. These changes should resolve both errors you're experiencing!

Hey
user P
I can help you with this
Here’s your graphql page query:

profiles {
  id: _key
  name
  bio
  image {
    asset {
      fluid(maxWidth: 700) {
        ...GatsbySanityImageFluid
      }
    }
  }
}
See how I’m using the
...GatsbySanityImageFluid
fragment here
that’s what I think you’re missing
Then here’s my custom Image component
import React, { useEffect, useRef, useState } from 'react';
import Image from 'gatsby-image';
import './Image.scss';

const ResponsiveImage = (props) => {
  const {
    image,
    className = '',
    style = {},
    onLoaded,
  } = props;

  const [loaded, setLoaded] = useState(false);
  const imgRef = useRef();

  useEffect(() => {
    if (onLoaded && imgRef.current && imgRef.current.state.imgLoaded) {
      onLoaded();
    }
  }, [imgRef.current, loaded]);

  return (
    <Image
      className={className}
      fluid={image.asset.fluid}
      alt={image.alt || ''}
      style={style}
      ref={imgRef}
      onLoad={() => setLoaded(true)}
    />
  );
};

export default ResponsiveImage;
You don’t need all that (eg. the onLoad handler), but its a nice little bit of functionality
Here’s a little extra
I would recommend you use
gatsby-plugin-sanity-image
It’s made by
user L
, and I wish I had used it earlier in my project, because it allows for extra control over images sourced from Sanity than
gatsby-source-sanity
Very nice, thanks so much for the help

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?