How to fetch array of images with GROQ in Sanity?
I would like to fetch the array of the Images, but i don't know how to fetch it with the groq correctly. So, i assumed that i should write like this:
return client.fetch(
groq`*[_type == 'page' && slug.current == $slug][0]{
_id,
_createdAt,
"mainImage": mainImage.asset->url,
"image": images[].asset->url, //I am also querying images array here. //Array of Images
title,
"slug": slug.current,
content,
alt
}`,
{slug}
)
}
Hovewer, when i am debugging my function, my images in the console written as "null". Hence, what i should wtite to get my all Array of the Images?
P.S. {
//Here is the input that i created for Images array inside my Sanity studio
name: "image",
title: "Image",
type: "array",
of: [{ type: 'image' }],
options: { hotspot: true },
},
The issue with your query is that you need to match the field name from your schema. Looking at your code, there's a mismatch between what you defined in your schema and what you're querying.
Your schema defines the field as:
name: "image", // This is the field nameBut you're querying images[] (with an 's'). You should query image[] to match your schema:
return client.fetch(
groq`*[_type == 'page' && slug.current == $slug][0]{
_id,
_createdAt,
"mainImage": mainImage.asset->url,
"images": image[].asset->url, // Changed from images[] to image[]
title,
"slug": slug.current,
content,
alt
}`,
{slug}
)The syntax image[].asset->url is correct - it:
- Maps over each item in the
imagearray - Dereferences the
assetreference using-> - Extracts the
urlfield from each asset
I've aliased it as "images" (plural) in the projection for clarity in your returned data, but the important part is reading from the correct image field name.
If you're still getting null after fixing this, check:
- That your documents actually have images in the
imagefield (check in Sanity Studio) - That the images are properly uploaded with asset references
- That you're querying published documents (drafts have
_idstarting with "drafts.")
You can also get more image data by expanding the projection:
"images": image[]{
"url": asset->url,
"alt": alt,
"hotspot": hotspot
}This gives you an array of objects with URL, alt text, and hotspot information for each image.
Show original thread5 replies
Was this answer helpful?
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.