How to access first element of array in Sanity query after API update?
I hear your frustration! The syntax you're using should still work in GROQ. The pattern relatedTasks[].value[0] is valid for accessing the first element of an array, so let me help you troubleshoot this.
Based on the recent API version 2025-02-19 update, the most likely culprit is the default perspective change. The API now defaults to perspective=published instead of perspective=raw, which means you'll only see published documents by default, not drafts.
Here are a few things to check:
1. Make sure your documents are published If you're working with draft content, you need to explicitly set the perspective:
// In your query configuration
const query = `*[_type == "yourType"] {
"relatedTask": relatedTasks[].value[0]
}`
// Add perspective parameter
client.fetch(query, {}, { perspective: 'previewDrafts' })2. Verify your array structure
Double-check that relatedTasks is actually an array and that value exists. Try debugging with:
*[_type == "yourType"] {
relatedTasks,
"firstTask": relatedTasks[0],
"firstValue": relatedTasks[0].value
}3. Alternative syntax options If the chained approach isn't working, try these alternatives:
// Using slice notation
"relatedTask": relatedTasks[0].value
// Or if value itself is an array
"relatedTask": relatedTasks[0].value[0]
// Or flattening first
"relatedTask": relatedTasks[][0].valueThe GROQ pipeline components documentation confirms that array access with [0] for the first element and chained dereferencing should work fine.
The most common issue after recent updates is the perspective change - if your related tasks are in draft state and you're not explicitly requesting drafts, they won't appear in your query results. Try adding perspective: 'previewDrafts' or perspective: 'raw' to your fetch options and see if that resolves it!
Show original thread3 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.