Get results and total count of Sanity records by GROQ

ayyash

Ayyash

Posted on February 26, 2022

Get results and total count of Sanity records by GROQ

To retrieve the results and the total, using GROQ for Sanity.IO, you need to start by casting to your model like this (this is passed in query)

query = `{
    "items": *[_type == "post"] | order(publishedAt desc)[1...5],
     "total": count(*[_type == "post"]) 

}`
Enter fullscreen mode Exit fullscreen mode

The result looks like this

{
    "ms": 65,
    "query": "...",
    "result": {
        "items": [
            {...}
        ],
        "total": 34
    }
}
Enter fullscreen mode Exit fullscreen mode

It looks obvious, but I had to read How Queries Work all the way to the end to figure out I can project my own outside model. Hope this helps someone.

RESOURCES

💖 💪 🙅 🚩
ayyash
Ayyash

Posted on February 26, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related