Unable to resolve image URL from source (undefined) in Sanity with React

4 replies
Last updated: Jul 8, 2022
Question: I am getting an error that is caused by the img tag and cannot find anything online about a fix. Trying to resolve error “urlForImage.ts:43 Uncaught Error: Unable to resolve image URL from source (undefined)” using Sanity and React.
I am running into an error using Sanity with Javascript and React. The app is a personal portfolio site and I have successfully pulled data from Sanity for 3 other sections. Now that I am working on the Testimonials section, I am trying to pull 2 images (jpegs) that currently loaded in Sanity Studio: testimonials > imgurl In my return statement, I am checking for length of testimonials so that I only fetch if at least one is present. Inside the image tag, I am using
src={urlFor(testimonials[currentIndex].imgurl)}

Code Block:


return (
<>
  {testimonials.length && (
    <>
      <div className="app__testimonial-item app__flex">
        <img src={urlFor(testimonials[currentIndex].imgurl)} alt="testimonial" />            
      </div>
    </>
  )}
</>
1. urlFor is the function used to fetch images off Sanity, as per their documentation.

2. currentIndex is the useState inside of the Testimonial function, which acts as the container component for this section of the website. It will keep track of the state of the image being displayed and will cycle through others with a clickable action (code not present here)



Question: I am getting an error that is caused by the img tag and cannot find anything online about a fix.

**ERROR MESSAGE**:
react-dom.development.js:20085 The above error occurred in the &lt;img&gt; component:
at img
at div
at Testimonial (
http://localhost:3000/main.20b2c7aaa42080546b80.hot-update.js:37:90 ) at div
at VisualElementHandler (
http://localhost:3000/static/js/bundle.js:119980:38 ) at MotionComponent (
http://localhost:3000/static/js/bundle.js:119880:20 ) at HOC
at div
at div
at HOC
at div
at App
Consider adding an error boundary to your tree to customize error handling behavior.
Visit
https://reactjs.org/link/error-boundaries to learn more about error boundaries.

Error Message

Uncaught Error: Unable to resolve image URL from source (undefined)
at urlForImage (urlForImage.ts
:43:1) at ImageUrlBuilder.url (builder.ts
:229:1) at ImageUrlBuilder.toString (builder.ts
:234:1) at setValueForProperty (react-dom.development.js
:672:1) at setInitialDOMProperties (react-dom.development.js
:8931:1) at setInitialProperties (react-dom.development.js
:9135:1) at finalizeInitialChildren (react-dom.development.js
:10201:1) at completeWork (react-dom.development.js
:19470:1) at completeUnitOfWork (react-dom.development.js
:22815:1) at performUnitOfWork (react-dom.development.js
:22787:1)

[1]:
https://stackoverflow.com/questions/69031649/error-unable-to-resolve-image-url-from-source-null
AI Update

The error "Unable to resolve image URL from source (undefined)" means that testimonials[currentIndex].imgurl is undefined when your component tries to render. This is a common timing issue in React when working with Sanity data.

The Problem

Your conditional check {testimonials.length && ( evaluates to truthy when the array has items, but it doesn't guarantee that the current item or its imgurl property exists. The array might be populated, but currentIndex could be pointing to an invalid index, or the imgurl field might not be populated in your Sanity document.

Solutions

1. Add proper null/undefined checks:

return (
  <>
    {testimonials.length > 0 && testimonials[currentIndex]?.imgurl && (
      <>
        <div className="app__testimonial-item app__flex">
          <img 
            src={urlFor(testimonials[currentIndex].imgurl)} 
            alt="testimonial" 
          />            
        </div>
      </>
    )}
  </>
)

2. Initialize currentIndex properly:

Make sure your currentIndex state starts at 0 and is valid:

const [currentIndex, setCurrentIndex] = useState(0);

3. Verify your GROQ query includes the image asset:

When fetching testimonials from Sanity, make sure you're including the image asset reference properly:

const query = '*[_type == "testimonials"]{
  _id,
  name,
  company,
  imgurl {
    asset-> {
      _id,
      url
    }
  }
}';

4. Check your Sanity schema:

Ensure your testimonials schema has the image field defined correctly:

{
  name: 'imgurl',
  title: 'Image',
  type: 'image',
  options: {
    hotspot: true,
  }
}

5. Debug what you're receiving:

Add a console.log to see what data you're actually getting:

console.log('Current testimonial:', testimonials[currentIndex]);
console.log('Image URL field:', testimonials[currentIndex]?.imgurl);

The most likely culprit is that your image field is either not being queried properly from Sanity, or the document doesn't have an image uploaded yet. The urlFor function from @sanity/image-url expects a valid image asset reference object, not undefined.

If you're still having issues after these checks, verify that:

  • The images are actually uploaded in Sanity Studio
  • Your urlFor function is set up correctly with your project ID and dataset
  • The field name in your query matches exactly what's in your schema (you're using imgurl - make sure that's the correct field name)
Show original thread
4 replies
Are you passing an entire asset to your
urlFor
or a url?
Hi! I’m not sure what you mean by asset. This is my client.js file which I am using to connect to Sanity client with React app

import sanityClient from "@sanity/client";
import imageUrlBuilder from "@sanity/image-url";

export const client = sanityClient({
  projectId: process.env.REACT_APP_SANITY_PROJECT_ID,
  dataset: "production",
  apiVersion: "2022-06-21",
  useCdn: true,
  token: process.env.REACT_APP_SANITY_TOKEN,
});

const builder = imageUrlBuilder(client);

export const urlFor = (source) => builder.image(source);
That part looks right! What I mean is this line:
testimonials[currentIndex].imgurl
. It looks like you're passing a url that is a string to the builder instead of the
asset
object that Sanity sets on an image field.
@*RD (she/they) * - THANK YOU! Ok, so after a few hours of tinkering, your comment made a light go off. You are absolutely right, I was not thinking about what I was passing to the image field. I went back to the SCHEMA for Sanity on my backend, and noticed that there was a typo for that field. I was calling on testimonials[currentIndex].imgurl when it was actually mis-spelled on the backend as ” imageurl “.
There are a bunch of other error messages to deal with now, but this was a big one that had me stuck for days, so thank you, very much!

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?