🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

How to get the previous and next article based on publish date in a Groq query

10 replies
Last updated: Jul 31, 2022
me again 😂
is there a way to get prev/next of a type in a Groq query?

say i have
*[_type == 'article'] | order(publishDate desc)
... can i get the prev/next by extending this query?
Jul 30, 2022, 10:23 PM
You may be interested in this documentation page: Paginating with GROQ
Jul 30, 2022, 10:58 PM
been reading and re-reading this to parse through how to execute this.
its talking about creating pagination through a huge number of documents (ie:
*[_type == 'article']

i'm looking to do this on a single article... get the article before and after it (based on my
trying to understand how to use something like
const currentArticle = article.publishDate
and then find article directly before/after this date.
Jul 31, 2022, 10:46 AM
maybe something like?
*[_type == "article" && publishDate > $currentArticle] | order(publishDate) [0]

Jul 31, 2022, 10:48 AM
so i've tested this in Vision in my studio and it works when i give it the
as a string.
so i think i'm needing to understand the best way to pass a variable into my query
Jul 31, 2022, 11:19 AM
got them working by doing the following:

const thisDate = post.publishDate
const nextPage = await client.fetch(`*[_type == "article" && publishDate > "${thisDate}"] | order(publishDate) [0] {title, publishDate, slug}`)
const prevPage = await client.fetch(`*[_type == 'article' && publishDate < "${thisDate}"] | order(publishDate desc) [0] {title, publishDate, slug}`)
wondering if there is a more efficient way ... or perhaps pulling this into a function.

not sure if its necessary, but this seems verbose
Jul 31, 2022, 11:36 AM
Ah, if you just want the previous and next, yes, that’s how I would do it.
Jul 31, 2022, 1:48 PM
Note that if multiple articles could be published on the exact same
, you will have to do a little more work here.
Jul 31, 2022, 1:48 PM
yeah, i was thinking the same... and would follow the directions from the link you gave above to incorporate the
likely will add that shortly, but wanted to get the basics working first
Jul 31, 2022, 1:50 PM
actually, the more i think about this, i'm not sure i have to adjust anything.
unless there were 2 posts with the EXACT date AND time... which would basically be impossible since i'm the only editor and only use the studio and i set the date/time as a custom field.

but in a bigger, code based "make it foolproof" way i should probably update the query ...

Jul 31, 2022, 2:55 PM
It is unlikely, true. 🙂
Jul 31, 2022, 3:24 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?