Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Retrieving Items from an Array in the Order They are Displayed in the Studio

1 replies
Last updated: Jan 5, 2023
Hi all,Does anyone know how to retrieve items from an array in the order they are displayed in the studio?

I'm working on a website with an image gallery. The images are being pulled from an array of references, and it's important to be able to set the order in the studio (given the helpful drag and drop functionality of the array) and have the images on the front-end reflect that order.

When I GROQ the references and get the image urls they appear to be in a random order. I looked at the ordering documentation in the Query Cheat Sheet but they only seem to have solutions for ordering based on specific attributes, which I don't believe is helpful in my case, unless there is an attribute I'm unaware of that corresponds to the order in studio?

Thank you!
Jan 5, 2023, 10:47 PM
Ah nvm, I realized I was using a much more convoluted way of querying than I needed to, which meant the order in the desk wasn't being taken into account.
I was doing this:

"works": *[_type == "work" && public && references(^._id)]{
   		title,
   		defined(workImage.name) => {"caption": workImage.name},
   		defined(workImage.altText) => {"altText": workImage.altText}, 
   		"imageUrl": workImage.attachment.asset->url
   }
Which was grabbing the works based on their back reference to each artist, when really all I needed to do was:

works[]->{
      title,
   		defined(workImage.name) => {"caption": workImage.name},
   		defined(workImage.altText) => {"altText": workImage.altText}, 
   		"imageUrl": workImage.attachment.asset->url
   }
This grabs the referenced works from the artist document, which by default seems to be preserving the order.
Jan 5, 2023, 11:32 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?