Skip to content

Commit 957cdf3

Browse files
committed
✨ feat: add pagination to blog
1 parent 6b1fafb commit 957cdf3

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

gatsby-node.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,30 @@ exports.createPages = async ({ graphql, actions }) => {
8585
fromPath: `/chat`,
8686
toPath: `https://discord.gg/KZRDXmTm9v`,
8787
})
88+
89+
createRedirect({
90+
fromPath: `/blog/1/`,
91+
toPath: `/blog/`,
92+
})
93+
94+
// Create blog-list pages
95+
const blogPostListPage = path.resolve('./src/templates/blog-post-list.js');
96+
const blogPosts = allMarkdown.data.allMarkdownRemark.edges.filter(({ node }) => node.fields.slug.includes('blog/'));
97+
const blogPostsPerPage = 3
98+
const numPages = Math.ceil(blogPosts.length / blogPostsPerPage)
99+
100+
Array.from({ length: numPages }).forEach((_, i) => {
101+
createPage({
102+
path: i === 0 ? `/blog` : `/blog/${i + 1}`,
103+
component: blogPostListPage,
104+
context: {
105+
limit: blogPostsPerPage,
106+
skip: i * blogPostsPerPage,
107+
numPages,
108+
currentPage: i + 1,
109+
},
110+
})
111+
})
88112
};
89113

90114
function pad(n) {
Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,12 @@ function Blog({ data }) {
4646
export default Blog;
4747

4848
export const pageQuery = graphql`
49-
query blogList {
49+
query blogList ($skip: Int!, $limit: Int!) {
5050
allMarkdownRemark(
5151
filter: { fields: { slug: { regex: "/blog/" } } }
5252
sort: { frontmatter: { date: DESC } }
53+
limit: $limit
54+
skip: $skip
5355
) {
5456
edges {
5557
node {

0 commit comments

Comments
 (0)