Discussion on whether to use one or two queries when fetching data in Sanity.io

5 replies
Last updated: Jun 11, 2023
I have another question, which set of queries is better? The first query gets everything all at once, but I keep calling it every single time I paginate

export const authors = groq`
  *[_type == 'author' && slug.current == $slug && archived == false][0]{
    ${authorFields}
    "posts": *[_type == 'post' && references(^._id)] | order(publishedAt desc, _updatedAt desc)[(($pageIndex - 1) * 10)...$pageIndex * 10]{
      ${litePostFields}
    },
    "totalPosts": count(*[_type == 'post' && references(^._id)])
  }
`
or is doing something like this where I have two queries, but I don't keep fetching the author data over and over again

export const authors = groq`
  *[_type == 'author' && slug.current == $slug && archived == false][0]{
    ${authorFields}
  }
`

export const authorsPosts = groq`
*[_type == 'author' && slug.current == $slug && archived == false][0]{
  "posts": *[_type == 'post' && references(^._id)] | order(publishedAt desc, _updatedAt desc)[(($pageIndex - 1) * 10)...$pageIndex * 10]{
    ${litePostFields}
  },
  "totalPosts": count(*[_type == 'post' && references(^._id)])
}
`
My
assumption is it would be better to have two separate calls 🤔
Jun 10, 2023, 3:22 AM
IMHO, there's no significant difference since both queries need to fetch the author.
Jun 10, 2023, 11:33 AM
What I would consider doing is changing the second query to be:
*[_id == $id][0] {
…because presumably you already have the author object and know its ID when you call this.
Jun 10, 2023, 11:34 AM
I strongly recommend using IDs for filtering rather than slugs, whenever possible.
Jun 10, 2023, 11:34 AM
Ah good to know! I updated the second query to be
export const authorsPosts = groq`
*[_type == 'author' && _id == $authorId && archived == false][0]{
  "posts": *[_type == 'post' && references(^._id)] | order(publishedAt desc, _updatedAt desc)[(($pageIndex - 1) * 10)...$pageIndex * 10]{
    ${litePostFields}
  },
  "totalPosts": count(*[_type == 'post' && references(^._id)])
}
`
Or can I just eliminate
_type == 'author'
and the
archived == false
part? I guess I wasn't sure if there was a potential for collision anywhere
Jun 10, 2023, 10:16 PM
IDs are unique, so you don't need the other parts of the filter.
Jun 11, 2023, 11:34 AM

Sanity– build remarkable experiences at scale

The Sanity Composable Content Cloud is the 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?

Categorized in