2

I am trying to create pagination for my blog in Gatsby. I have managed to get the pagination to kinda work.

When I go to localhost:8000/posts I get the whole list of my blog posts. When I go to localhost:8000/posts/2 I get the list of paginated posts, only showing 3 posts.

When I try to access the post say http://localhost:8000/posts/loading-css-via-prefers-color-scheme/ I get a TypeError: Cannot read property 'page' of undefined which is throwing me off as this is my dir:

│   ├── posts
│   │   ├── breaking-jekyll-posts-into-years.md
│   │   ├── cleaning-up-git.md
│   │   ├── converting-dates-from-api-repsonses-in-django.md
│   │   ├── css-dark-mode.md
│   │   ├── generating-ssh-keys.md
│   │   ├── getting-api-data-into-your-templates-with-django.md
│   │   ├── imgs
│   │   ├── loading-css-via-prefers-color-scheme.md
│   │   ├── sticky-footer-with-flexbox.md
│   │   └── writing-a-changelog.md
│   └── templates
│       ├── post-list.js
│       └── post.js

This is my template for the paginated posts

And this is my gatsby node file

I have two questions following on from the above.

  1. Where am i going wrong, in relation to being able to click through to the actual post.
  2. How can i display the paginated posts on the url localhost:8000/posts instead of the whole lot...is this just a templating issue I am not seeing? Can i use a template within a page? Or can i use a template as an page?
mrpbennett
  • 1,527
  • 15
  • 40

1 Answers1

2

You were overwriting your first module.exports.createPages with the second in gatsby-node

const path = require('path');
const { createFilePath } = require('gatsby-source-filesystem');

// CREAT SLUGS FOR .MD PAGES
exports.onCreateNode = ({ node, getNode, actions }) => {
    const { createNodeField } = actions;
    if (node.internal.type === 'MarkdownRemark') {
        const slug = createFilePath({ node, getNode, basePath: 'pages' });
        createNodeField({
            node,
            name: 'slug',
            value: slug,
        });
    }
};

// DYNAMICALLY CREATE PAGES FOR EACH POST
module.exports.createPages = async ({ graphql, actions, reporter }) => {
    const { createPage } = actions;
    const result = await graphql(`
        query {
            allMarkdownRemark {
                edges {
                    node {
                        fields {
                            slug
                        }
                    }
                }
            }
        }
    `);

    // Handle errors
    if (result.errors) {
        reporter.panicOnBuild('Error while running GraphQL query.');
        return;
    }

    // Create the pages for each markdown file
    const postTemplate = path.resolve('src/templates/post.js');
    result.data.allMarkdownRemark.edges.forEach(({ node }) => {
        createPage({
            component: postTemplate,
            path: `${node.fields.slug}`,
            context: {
                slug: node.fields.slug,
            },
        });
    });


    // PAGINATION FOR BLOG POSTS

    const postsResult = await graphql(
        `
            {
                allMarkdownRemark(
                    sort: { fields: [frontmatter___date], order: DESC }
                    limit: 1000
                ) {
                    edges {
                        node {
                            fields {
                                slug
                            }
                        }
                    }
                }
            }
        `
    );

    if (postsResult.errors) {
        reporter.panicOnBuild('Error while running GraphQL query.');
        return;
    }

    // Create blog-list pages
    const posts = postsResult.data.allMarkdownRemark.edges;
    const postsPerPage = 3;
    const numPages = Math.ceil(posts.length / postsPerPage);
    Array.from({ length: numPages }).forEach((_, i) => {
        createPage({
            path: i === 0 ? '/posts' : `/posts/${i + 1}`,
            component: path.resolve('./src/templates/post-list.js'),
            context: {
                limit: postsPerPage,
                skip: i * postsPerPage,
                numPages,
                currentPage: i + 1,
            },
        });
    });
};
ksav
  • 20,015
  • 6
  • 46
  • 66
  • 1
    Thanks dude this worked...simple spot when you know what you're doing I guess lol... – mrpbennett Oct 08 '19 at 15:27
  • whats the best way to now display the paginated posts instead of the list of all posts. Do I just switch the template for the page? – mrpbennett Oct 08 '19 at 17:33
  • Maybe delete `src/pages/posts.js` and just create pages in gatsby-node like you already are `createPage({path: \`/posts/${i + 1}]\`, ...})` – ksav Oct 08 '19 at 19:29
  • If you run into any problems, try deleting `.cache` and `public` and running gatsby develop again. – ksav Oct 08 '19 at 19:37
  • 1
    YES!! that worked!! amazing...thanks dude...now I have to sort the pagination numbering at the bottom ...step by step this is working lol – mrpbennett Oct 09 '19 at 10:15
  • Great job. If you get stuck on something else, just post another question. – ksav Oct 09 '19 at 11:57
  • well funny you say that.. I am trying this tut https://nickymeuleman.netlify.com/blog/gatsby-pagination but I can't put the const's in the class. – mrpbennett Oct 09 '19 at 15:48
  • Link to the new question here, and I'll take a look tomorrow – ksav Oct 09 '19 at 20:41
  • https://stackoverflow.com/questions/58318868/unable-to-use-const-within-a-class-in-react thanks man – mrpbennett Oct 10 '19 at 08:45