Unlock seamless workflows and faster delivery with our latest releases โ€“ get the details

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
publishDate
field).
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
$currentArticle
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
publishDate
, 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
lastId
part.
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 ...

lol
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?