How to get 'previous post' from pagination

I’m attempting to add ‘next’ and ‘previous’ links that navigate between pages in the same content model. The content model can be ordered by the editor with drag and drop.

I’ve figured out how to apply the ‘next’ from one of your support articles, using skip and first. However, I’m struggling to do the same for ‘previous’ as it doesn’t seem like you can decrement a variable.

My working ‘next’ query looks like the following:

nextProject: allProjects(
    orderBy: position_ASC 
    skip: $position 
    first: 1
) {
    title
}

I’d expect to be able to do something similar for the previous query, but get a parsing error around trying to add the minus symbol.

prevProject: allProjects(
    orderBy: position_ASC 
    skip: $position - 1
    first: 1
) {
    title
}

Not sure if it’s possible to write the query in this way, so any help would be appreciated :blush:

Managed to solve this by two separate queries. The first to get the current post’s position. Then -2 (I realised, not -1 as this would skip to the current position) to that value and use this as $position for this second query. Was obviously thinking about this in the wrong way :slightly_smiling_face:

@lbirchall, glad that worked for you!

Just as an alternative / for future reference, you can also use several variables while forming your query (and let your client do the math):

query MyQuery($position: IntType, $lastPosition: IntType, $nextPosition: IntType) {
  currentRecord: unit(filter: {position: {eq: $position}}) {
    ...UnitFragment
  }
  prevRecord: unit(filter: {position: {eq: $lastPosition}}) {
    ...UnitFragment
  }
  nextRecord: unit(filter: {position: {eq: $nextPosition}}) {
    ...UnitFragment
  }
}

fragment UnitFragment on UnitRecord {
  id
  name
  position
}

Variables:

{
  "position": 2,
  "lastPosition": 1,
  "nextPosition": 3
}

And depending on your framework, like if you’re using something like Next.js to prebuild pages and some sort of global router + state for routing, it might make sense to just prefetch all the projects and their positions ahead of time, store that in the global state / context and pass that along to the router, so it doesn’t have to calculate prev/next pages on each client page load (which might take a couple seconds).

1 Like