0

As described, I would like to add pagination on a page, where I'm fetching data from Sanity. I'm using getStaticProps for fetching data, and I know that getStaticProps works at build time, so how can I add pagination? Should I kind of pre-build pages?

My code looks like this:

export const getStaticProps = async () => {
  const textures = await clientSanity.fetch(`*[_type == "texture"] | order(publishedAt desc){
      _id,
      title,
      'slug': slug.current,
      mainImage{asset->{_id, url}},
  }`);
  const categories = await clientSanity.fetch(`*[_type == "category"] | order(title asc){
      _id,
      title,
      'slug': slug.current,
  }`);

  return {
    props: {
      textures,
      categories,
    },
  };
};

I really don't know where to start.

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Ivan93
  • 11
  • 1
  • 2

2 Answers2

1

Pagination - in case someone didn't understand what it actually is.

In your example you are fetching all textures and categories server side. With this approach you don't have to paginate, because you already loaded all data. Sanity billing will love you.

Sanity already has a pretty solid documentation on pagination you can follow along. But here in short.

Limit the items you get from server to 10:

*[_type == "texture"] | order(publishedAt desc) [0...10]
*[_type == "category"] | order(title asc) [0...10]

Store the _id of your last item and call this query client side:

*[_type == "texture" && _id > $lastTextureId] | order(_id) [0...20] {
  _id, title, body
}
*[_type == "category" && _id > $lastCategoryId] | order(_id) [0...20] {
  _id, title, body
}
nixn
  • 1,337
  • 3
  • 16
  • 33
0

For paginated feeds—loading more items on the same page—the pattern I've followed is to load the initial CMS payload with SSG and then do the pagination on the client-side.

A quick and dirty example with SSR can be found here: https://codesandbox.io/s/muddy-snow-bguux?file=/pages/index.js

This should also work with SSG.

rionmartin
  • 35
  • 4
  • [Pagination](https://developers.google.com/search/docs/specialty/ecommerce/pagination-and-incremental-page-loading) is a concept to reduce the loading time of a website and to save server resources/bandwidth by reducing payload size. This is definitely a misleading approach that should never land into production, as this approach is literally solving none of the problems mentioned. The only thing you are potentially solving here is to reduce the resources needed for rendering react. – nixn Oct 14 '22 at 12:40