👀 See Sanity in action: Watch product demo now →

How to Create Pagination for a Collection of Posts

3 replies
Last updated: Feb 11, 2021
looking for help with setting up a “page of posts” … its a document type archive page, but it exists as a page itself (in order to get hero details, etc) and then i want to query for all the documents of the type… the area i’m struggling with is paginating it, so something like
/resources/page/2
etc
Feb 8, 2021, 8:57 PM
I think this should help you, it’s how we generate a paginated “category” section for our site:
exports.createBlogPostPagesSanity = async ({ graphql, actions, reporter }) => {
  const { createPage } = actions;

  const blogPostTemplateSanity = path.resolve(`src/templates/blog-post.js`);

  const newsIndexTemplate = path.resolve(`src/templates/news-index.js`);

  // From <https://github.com/sanity-io/example-company-website-gatsby-sanity-combo/blob/master/web/gatsby-node.js>
  const result = await graphql(`
    query {
      allSanityPost(filter: { slug: { current: { ne: null } } }) {
        nodes {
          id
          route
          category {
            name
          }
        }
      }
    }
  `);

  if (result.errors) throw result.errors;

  const sanityPosts = result.data.allSanityPost.nodes || [];

  <http://reporter.info|reporter.info>(`Processing ${sanityPosts.length} blog posts from <http://Sanity.io|Sanity.io>`);

  sanityPosts.forEach((post) =&gt; {
    createPage({
      path: post.route,
      component: blogPostTemplateSanity,
      context: {
        id: post.id,
      },
    });
  });

  const postsPerPage = 20;
  const categories = ['national', 'state', 'resistbot'];
  for (let category of categories) {
    const categoryPosts = sanityPosts.filter(
      (post) =&gt; post.category.name === category
    );
    const numPages = Math.ceil(categoryPosts.length / postsPerPage) || 1;
    Array.from({
      length: numPages,
    }).forEach((_, i) =&gt; {
      createPage({
        path:
          i === 0
            ? `${BASE_URL_BLOG}/${category}`
            : `${BASE_URL_BLOG}/${category}/${i + 1}`,
        component: newsIndexTemplate,
        context: {
          limit: postsPerPage,
          skip: i * postsPerPage,
          numPages,
          currentPage: i + 1,
          category,
        },
      });
    });
  }
};
Feb 11, 2021, 2:13 PM
Feb 11, 2021, 2:14 PM
thanks! i’ll check this out
Feb 11, 2021, 3:12 PM

Sanity.io – build remarkable experiences at scale

Sanity is a customizable solution that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.