pixelstew / gatsby-paginate Goto Github PK
View Code? Open in Web Editor NEWA simple library for paginating posts in Gatsby js.
License: GNU General Public License v3.0
A simple library for paginating posts in Gatsby js.
License: GNU General Public License v3.0
Updated my dependencies (gatsby, plugins etc) to the lastest releases today and am now getting this error at build:
ERROR #11323
Your site's "gatsby-node.js" must set the page path when creating a page
It happens on this code:
createPaginatedPages({
edges: result.data.allMarkdownRemark.edges,
createPage: createPage,
pageTemplate: 'src/templates/index.js',
pageLength: 20,
})
Looking at the error - it's the very first page.
Path is calculated in paginate as:
path:
typeof buildPath === `function`
? buildPath(pageIndex, pathPrefix)
: buildPaginationRoute(pageIndex, pathPrefix),
Here I am not passing a buildPath function - so that is null and therefore it calls buildPaginationRoute.
const buildPaginationRoute = (index, pathPrefix) =>
index > 1 ? `${pathPrefix}/${index}` : pathPrefix
Index is the empty string on the first page (I think).
So this returns just pathPrefix - but - I am not using pathPrefix for the main index of the site - so that's the empty string.
I suspect that it's related to this change in gatsby:
gatsbyjs/gatsby@44654be#diff-c739d0ad63537276e8fc320522a8b985
If you look at the code there you can see that before the change - if the path was the empty string it would do this:
console.log(chalk.bold.red(message))
console.log(``)
console.log(page)
But now it does this:
report.panic({
id: `11323`,
context: {
pluginName: name,
pageObject: page,
message,
},
})
If I understood the gatsby code then it means that after this change - it will no longer log and continue but abort a build if we call paginate with no pathPrefix and no buildPath function when creating the first page?
So I think the way this is supposed to work is that I replace createPages with something like this:
createPaginatedPages({
edges: result.data.allMarkdownRemark.edges,
createPage: createPage,
pageTemplate: './src/templates/index.js'
});
Now I am not sure if the template is for the index page or the post. If for the index, then how do i define the template for the post? Also, how about the other things I want to pass in the context?
Trying to use path prefix to assist me with localization. What I am finding is that the first page is always created at root '/' and subsequent pages are working correctly.
My developer 404, basically shows
/
/en/2
/en/3
/en/4
The path prefix is being ignored completely on the first page. Is this intended?
Sorry for the confusing title but it's the best way I could explain my problem in one sentence. Explanation below -
I'm using gatsby-paginate to show one post at a time on my homepage, like so -
When the next link is clicked it goes to the next post which is exactly what I want to happen.
However, I'm wanting to tease the next post on the present post page. Similiar to this -
I could update the pageLength: 2 which outputs two posts (which is what I want) but obviously the next link goes to the third and fouth post when I only want it to go to the second post and show the third as a teaser.
Is this possible to do with gatsby paginate or am I approaching it all wrong?
I pass in a string id context:
createPaginatedPages({
edges: node.thought,
createPage: createPage,
pageTemplate: tagTemplate,
context: {
id: node.id,
},
pageLength: 2,
pathPrefix: `tags/${node.slug}`,
buildPath: (index, pathPrefix) =>
index > 1 ? `${pathPrefix}/${index}` : `/${pathPrefix}`,
});
whose template has the following query:
export const pageQuery = graphql`
query tagQuery($id: String!) {
contentfulTag(id: { eq: $id }) {
… fields
}
}
`;
but I'm getting a GraphQL error saying GraphQLError: Variable "$id" of required type "String!" was not provided.
most likely because its not seeing the id variable because its inside of additionalContext
I’m able to pass $id in and use it in my query when i assign context differently:
context: Object.assign(
{
group,
pathPrefix,
first: isFirstPage(index),
last: isLastPage(index, groups),
index: index + 1,
pageCount: groups.length,
},
context
),
Is there a way to rewrite my graphQL query so that i can use the additionalContext?
My gatsby-node.js:
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`
})
const path = require("path")
const createPaginatedPages = require("gatsby-paginate")
exports.createPages = ({ graphql, actions }) => {
const { createPage } = actions
return new Promise((resolve, reject) => {
graphql(
`
{
allWordpressPost(limit: ${process.env.BLOG_LIMIT}) {
edges {
node {
id
slug
title
content
excerpt
date
modified
categories {
name
}
author {
name
}
featured_media {
localFile {
childImageSharp {
fluid {
src
srcSet
base64
sizes
aspectRatio
}
}
}
}
}
}
}
}
`
).then(result => {
if (result.errors) {
console.log(result.errors)
reject(result.errors)
}
createPaginatedPages({
edges: result.data.allWordpressPost.edges,
createPage: createPage,
pageTemplate: "./src/components/elements/blog/PostsTemplate.tsx",
pageLength: 5,
pathPrefix: "/blog"
})
result.data.allWordpressPost.edges.forEach(({ node }) => {
createPage({
path: "blog/" + node.slug,
component: path.resolve(
"./src/components/elements/blog/PostTemplate.tsx"
),
context: {
slug: node.slug,
imageSharp: node.featured_media,
title: node.title,
author: node.author.name,
categories: node.categories,
modified: node.modified,
content: node.content
}
})
})
resolve()
})
})
}
Template:
import { Link } from "gatsby"
import React from "react"
import { FaArrowAltCircleLeft, FaArrowAltCircleRight } from "react-icons/fa"
import styled from "styled-components"
import Layout from "../../layouts/Layout"
import BlogCard from "./BlogCard"
interface Props {
data: {
allWordpressPost: {
edges: {
node: Node
}
}
}
}
interface Node {
node: {
id: string
slug: string
title: string
content: string
excerpt: string
date: string
modified: string
}
}
const NavLink = props => {
if (!props.test) {
return <Link to={props.url}>{props.text}</Link>
} else {
return <span style={{ textDecoration: "line-through" }}>{props.text}</span>
}
}
export default function BlogIndex({ data, pathContext }: Props) {
const { group, index, first, last, pageCount } = pathContext
const previousUrl = index - 1 === 1 ? "" : (index - 1).toString()
const nextUrl = (index + 1).toString()
return (
<Layout sidebar={true}>
<BlogPostsWrapper>
<ul style={{ margin: "0", listStyleType: "none" }}>
{group.map(({ node }: Node) => (
<li key={node.id}>
<Link className="card-wrapper" to={"blog/" + node.slug}>
<BlogCard data={node} />
</Link>
</li>
))}
</ul>
</BlogPostsWrapper>
<StyledPagination>
<div className="previous-link">
<FaArrowAltCircleLeft className="arrow-left" />
<NavLink test={first} url={`blog/${previousUrl}`} text="Previous" />
</div>
<div className="next-link">
<NavLink test={last} url={`blog/${nextUrl}`} text="Next" />
<FaArrowAltCircleRight className="arrow-right" />
</div>
</StyledPagination>
</Layout>
)
}
const BlogPostsWrapper = styled.section`
width: 100%;
margin-bottom: 2rem;
`
const StyledPagination = styled.div`
display: flex;
justify-content: space-between;
margin-bottom: 2rem;
align-items: center;
.previous-link,
.next-link {
display: flex;
align-items: center;
}
.arrow-left,
.arrow-right {
font-size: 2rem;
margin: 0.5rem;
}
`
Everything works fine UNLESS refreshing from the first page of pages created by gatsby-paginate
What happens is when a user refreshes from the first page of created paginated pages, this plugin for example goes to URL: /blog
instead of https://www.website.com/blog
. If a user refreshes from the 2nd page, it works fine.
Any help would be greatly appreciated.
When I run gatsby build, the pathContext object becomes empty and I get the following error
TypeError: group is undefined
In my project I'm using in on a non-index page called blog. When I'm running dev mode it's works as expected and the pathContext object has the data. Everything works great until I build it.
I also setup a new bare bones test project using the index example and still running into the same issue when i build it vs develop
Here's the index.js file from the test project
import React, { Component } from "react"
import Link from "gatsby-link";
const NavLink = props => {
if (!props.test) {
return <Link to={props.url}>{props.text}</Link>
} else {
return <span>{props.text}</span>
}
}
class Home extends Component {
render() {
const data = this.props.data
const { group, index, first, last, pageCount } = this.props.pathContext
const previousUrl = index - 1 == 1 ? "" : (index - 1).toString()
const nextUrl = (index + 1).toString()
return (
<div>
<h1>Posts</h1>
{group.map(({ node }) => (
<div key={node.id}>
<h3>{node.title}</h3>
</div>
))}
<div className="previousLink">
<NavLink test={first} url={previousUrl} text="Go to Previous Page" />
</div>
<div className="nextLink">
<NavLink test={last} url={nextUrl} text="Go to Next Page" />
</div>
</div>
)
}
}
export default Home
export const pageQuery = graphql`
query homePageQuery {
allWordpressPost(sort: { fields: [date] }) {
edges {
node {
title
id
slug
}
}
}
}
`
When passing in a custom layout
prop, it is not applied to any of the generated pages for pagination.
Here is my code:
createPaginatedPages({
createPage: createPage,
edges: result.data.allMarkdownRemark.edges,
layout: 'Page',
pageLength: 5
pageTemplate: path.resolve("src/templates/posts.tsx")
});
Is it possible to add searching with pagination?
Ie. by using Algolia
Would be most helpful
Preferably with something like wordpress...
Thank you
Providing the 'count' for the number of page groups created would greatly ease the creation footers stating index of count.
e.g. Page 1 of 20
New parameter handed to the template from createPaginatedPages:
{
group: []
first: boolean,
last: boolean,
index: int,
count: int
}
hi i have a page that shows posts according to a tag. but right now it is without pagination:
for each tag i create a page:
tags.forEach(tag => { actions.createPage({ path:
/tags/${tag}/, component: singleTagTemplate, context : { tag } }) })
and in the page itself i have a graphql query to bring all posts for that tag:
query( $tag : String ){ allMarkdownRemark ( filter : {frontmatter : {tags: {eq: $tag}} } sort: { fields: [frontmatter___date], order: DESC } ){ totalCount edges{ node{ id excerpt frontmatter{ title tags description date author path published } } } } }
how can i include the plugin so it will be paginated?
best regards
First of all, thanks a lot for this plugin!
It looks like this feature already existed, but was later removed. Why?
Wouldn't it be enough to add context
as a source to Object.assign
call?
context: Object.assign(
{},
{
group,
pathPrefix,
...
},
context
)
?
Or, if there's a risk that user could accidentally overwrite pagination context, switch pagination props with context.
Would it be possible to add a config option for creating the paginated post listing outside of the root of the document?
For example, instead of being at 0.0.0.0:8000/
it could be at 0.0.0.0:8000/blog
Hi,
I am not sure if gatsby-paginate is the root cause but I narrowed down that the pagination somehow works on pathPrefix/2
but not no posts are listed on pathPrefix
.
Here's my gatsby-node.js
: https://github.com/ajmalafif/ajmalafif.com/blob/master/gatsby-node.js
Here's the pathPrefix/2
page that works somehow: https://5d2cb8dae6f14b0007f00f14--ajmalafif.netlify.com/journal/2
Here's the broken page: https://5d2cb8dae6f14b0007f00f14--ajmalafif.netlify.com/journal/
I am getting this 404 in console but I am not sure how and where to fix this.
I keep trying things out on gatsby-node.js
on createPaginatedPages
and I'm not sure if I'm looking at the right place to solve this.
那个……我不会说英语
我照这个readme做了然而各种报错我都快疯了
求一个demo::>_<::
谢谢!
In my blog I have the following pages:
I was able to implement pagination for the Index page but I would also like to do the same for the category and tags pages. How do I do that?
I created my site with pagination using the template in the readme, but I have found that the links to paginated index pages become wrong after refreshing a page, for example:
http://example.com/2/
and refresh the page, links to previous/next pages become something like http://example.com/2/1/
, http://example.com/2/3/
This problem seems to occur only when I build a static site, and not via gatsby develop
.
As a workaround, I've changed urls passed to NavLink
to the following ones to make them always link to the paths relative to the root path.
<div className="previousLink">
<NavLink test={first} url={`/${previousUrl}`} text="Go to Previous Page" />
</div>
<div className="nextLink">
<NavLink test={last} url={`/${nextUrl}`} text="Go to Next Page" />
</div>
I am not sure this is a problem related to Gatsby itself rather than gatsby-paginate though.
License in the package.json
file is ISC and the in Github repo is GPL. Which one is the actual license??
I managed to get gatsby-paginate working, but when I include
image {
sizes(maxWidth: 400) {
...GatsbyContentfulSizes
}
}
in my graphql query in gatsby-node.js, my development build fails. I've tried to include a graphql query in my template, but I get this error: GraphQLError: Variable "$id" of required type "String!" was not provided.
Everything works when I remove the image sizes query above. Is there a way to get gatsby-image working with pagination? I've been through the examples, but haven't found one yet.
Here's the relevant gatsby-node section. Thanks.
.then(() => {
graphql(
`
{
allContentfulSongs(limit: 1000) {
edges {
node {
id
slug
title
path
image {
id
#sizes(maxWidth: 200) {
# ...GatsbyContentfulSizes
#}
}
}
}
}
}
`
).then(result => {
if (result.errors) {
reject(result.errors)
}
const categoryTemplate = path.resolve(`./src/templates/category.js`)
createPaginatedPages({
edges: result.data.allContentfulSongs.edges,
createPage: createPage,
pageTemplate: categoryTemplate,
pageLength: 5,
pathPrefix: "songs",
buildPath: (index, pathPrefix) => index > 1 ? `${pathPrefix}/${index}` : `/${pathPrefix}`
})
_.each(result.data.allContentfulSongs.edges, edge => {
createPage({
path: `${edge.node.slug}/`,
component: slash(categoryTemplate),
context: {
id: edge.node.id,
},
})
})
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.