Unable to resolve image URL from source (undefined) in Sanity with React
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
urlForfunction 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 thread4 replies
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.