How to access first element of array in Sanity query after API update?

3 replies
Last updated: Apr 9, 2024
Hi all! I previously used a query like:
"relatedTask": relatedTasks[].value[0],
that worked nice. In a update of the API it seems to not longer work.
Anyone that could point me out how I can access the first element of the array and get the value?
AI 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].value

The 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 thread
3 replies
In the new parser, precedence was swapped, so this means:
relatedTasks[].(value[0])
I.e., the first element of each
.value
of the array. So to accomplish what you have before:
(relatedTasks[].value)[0]
Perfect, thanks! Is it other things like this in the new parser I should know about, or read somewhere?
It's probably in the changelog somewhere, but this was changed in 2021, so I'm not sure I can find it. πŸ™‚

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?