Search code examples
reactjspaginationgatsbyblogsstrapi

I want to create a pagination in gatsby and strapi but im failing miserably


This is my njoftime.js file, located in src/pages/njoftime.js in my Gatsby Website

import React from "react";
import { graphql, Link } from "gatsby";
import Header from "../components/header";
import Footer from "../components/footer";
import * as styles from "../styles/lajme.module.css";

const Njoftime = ({ data, pageContext }) => {
  const { currentPage, numPages } = pageContext;
  const isFirst = currentPage === 1;
  const isLast = currentPage === numPages;
  const prevPage = currentPage - 1 === 1 ? "/njoftime" : `/njoftime/${currentPage - 1}`;
  const nextPage = `/njoftime/${currentPage + 1}`;

  const articles = data.strapi.newsArticles.data;

  return (
    <div>
      <Header />
      <div className={styles.lajmeContainer}>
        <h2 className={styles.lajmeTitle}>Njoftime</h2>
        <div className={styles.lajmeArticles}>
          {articles.map((article, index) => (
            <div key={index} className={styles.lajmeArticle}>
              <Link to={`/lajme/${article.attributes.slug}`} className={styles.lajmeArticleLink}>
                <div className={styles.lajmeArticleImageWrapper}>
                  <img src={`http://52.91.185.238:1337${article.attributes.Cover.data.attributes.url}`} alt={article.attributes.title} className={styles.lajmeArticleImage} />
                </div>
                <div className={styles.lajmeArticleContent}>
                  <h3 className={styles.lajmeArticleTitle}>{article.attributes.title}</h3>
                  <p className={styles.lajmeArticleDescription}>{article.attributes.Description}</p>
                  <p className={styles.lajmeArticleDate}>
                    Published on: <time>{article.attributes.PublishDate}</time>
                  </p>
                </div>
              </Link>
            </div>
          ))}
        </div>
        <div className={styles.pagination}>
          {!isFirst && (
            <Link to={prevPage} rel="prev">
              ← Previous Page
            </Link>
          )}
          {Array.from({ length: numPages }, (_, i) => (
            <Link key={`pagination-number${i + 1}`} to={`/njoftime/${i === 0 ? "" : i + 1}`}>
              {i + 1}
            </Link>
          ))}
          {!isLast && (
            <Link to={nextPage} rel="next">
              Next Page →
            </Link>
          )}
        </div>
      </div>
      <Footer />
    </div>
  );
};

export const query = graphql`
  query($skip: Int!, $limit: Int!) {
    strapi {
      newsArticles(sort: "PublishDate:desc", _start: $skip, _limit: $limit) {
        data {
          attributes {
            title
            Description
            PublishDate
            slug
            Cover {
              data {
                attributes {
                  url
                }
              }
            }
          }
        }
      }
    }
  }
`;


export default Njoftime;

This is my gatsby-node.js

const path = require("path");

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions;

  // Fetch all news articles
  const newsArticlesResult = await graphql(`
    {
      strapi {
        newsArticles {
          data {
            attributes {
              slug
            }
          }
        }
      }
    }
  `);

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

  // Create individual news article pages
  newsArticlesResult.data.strapi.newsArticles.data.forEach(({ attributes }) => {
    createPage({
      path: `/lajme/${attributes.slug}`,
      component: path.resolve(`src/templates/article.js`),
      context: {
        slug: attributes.slug,
      },
    });
  });

  // Pagination for njoftime
  const articles = newsArticlesResult.data.strapi.newsArticles.data;
  const articlesPerPage = 10; // Adjust based on your preference
  const numPages = Math.ceil(articles.length / articlesPerPage);

  Array.from({ length: numPages }).forEach((_, i) => {
    createPage({
      path: i === 0 ? `/njoftime` : `/njoftime/${i + 1}`,
      component: path.resolve("src/pages/njoftime.js"), // Ensure this path points to your njoftime template
      context: {
        limit: articlesPerPage,
        skip: i * articlesPerPage,
        numPages,
        currentPage: i + 1,
      },
    });
  });
};

I want to create a pagination logic for my njoftime.js and i keep going through the strapi documentation, but i still keep getting this error: Error when running my gatsby website

I expect a pagination logic, but instead i get these errors that i do not know what to do with since the strapi documentation and chatgpt v4 are suggesting the same solution to the problem which i have tried and it doesn't work.


Solution

  • You're querying the gatsby's graphql instance and not the strapi's API. The basic gatsby flow is

    1. Source the data from somewhere and create graphql nodes - Strapi in your case
    2. Query the graphql
    3. Use the queried data in the page templates

    So, all your graphql queries are working against the local graphql instance and not against the Strapi API. See the gatby's documentation for pagination implementation in gatsby.