Skip to content

Instantly share code, notes, and snippets.

@blakewilson
Created February 16, 2023 15:38
Show Gist options
  • Save blakewilson/b9e72d944ed0b096847b92ebb59019d3 to your computer and use it in GitHub Desktop.
Save blakewilson/b9e72d944ed0b096847b92ebb59019d3 to your computer and use it in GitHub Desktop.
Faust Next.js file based page for offset pagination
import { gql, useQuery } from '@apollo/client';
import { getNextStaticProps } from '@faustwp/core';
/**
* How many posts you want to display per page
*/
export const POSTS_PER_PAGE = 2;
/**
* Calculates the "offset" by multiplying
* the amount of pages by the posts per page
*
* @param {number} pageNumber
* @returns
*/
function getOffsetFromPageNumber(pageNumber) {
return pageNumber === 1 ? 0 : (pageNumber - 1) * POSTS_PER_PAGE;
}
export default function Page(props) {
// Get our data from the cache
const { data } = useQuery(Page.query, {
variables: {
postsPerPage: POSTS_PER_PAGE,
offset: getOffsetFromPageNumber(props.pageNumber),
},
});
return (
<>
<p>Total Posts: {data.posts.pageInfo.offsetPagination.total}</p>
<ul>
{data.posts.nodes.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</>
);
}
/**
* Our page's Query
*/
Page.query = gql`
query OffsetPaginatedQuery($postsPerPage: Int, $offset: Int) {
posts(
where: { offsetPagination: { size: $postsPerPage, offset: $offset } }
) {
pageInfo {
offsetPagination {
hasMore
hasPrevious
total
}
}
nodes {
id
title
}
}
}
`;
/**
* Our GraphQL variables for our above query. postsPerPage and the offset
*/
Page.variables = ({ params }) => {
const { pageNumber } = params;
return {
postsPerPage: POSTS_PER_PAGE,
offset: getOffsetFromPageNumber(pageNumber),
};
};
export function getStaticProps(ctx) {
/**
* @link https://faustjs.org/docs/next/reference/getNextStaticProps
*/
return getNextStaticProps(ctx, {
Page,
props: {
pageNumber: ctx.params.pageNumber,
},
});
}
export function getStaticPaths(ctx) {
return {
paths: [],
fallback: 'blocking',
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment