Bi-directional pagination hook for use in React using GraphQL & the Relay cursor-based pagination. Expecting an Apollo useLazyQuery
function. Thanks to a blog post by Tim Specht for the inspiration.
$ npm i @itzsaga/use-lazy-pagination
or
$ yarn add @itzsaga/use-lazy-pagination
The hook expects a single argument, the query function returned from the @apollo/react-hooks
useLazyQuery
hook.
const { goBack, goForward } = useLazyPagination(queryPosts);
The hook returns an object with 4 things on it.
Return Value | Description |
---|---|
currentPage | The current page you are on in the stack, defaults to 1 |
goBack | A function that moves you back a page |
goForward | A function that move you forward a page |
resetPagination | A function that resets the pagination state |
Note: goForward
expects a single argument of the endCursor
provided in the pageInfo
from the query. This is how the stack is built.
import React from "react";
import { useLazyQuery } from "@apollo/react-hooks";
import useLazyPagination from "@itzsaga/use-lazy-pagination";
function App() {
const [ queryPosts, { data, error, loading } ] = useLazyQuery(QUERY_POSTS);
const { currentPage, goBack, goForward, resetPagination } = useLazyPagination(
queryPosts
);
if (error) return <div>Error.</div>;
if (loading) return <div>Loading...</div>;
return (
<div>
<button disabled={currentPage === 1} onClick={() => goBack()}>
Back
</button>
<div>You are on page {currentPage}.</div>
<button onClick={() => goForward(data.Posts.pageInfo.endCursor)}>
Forward
</button>
</div>
);
}
Bug reports and pull requests are welcome on GitHub at https://github.com/itzsaga/use-lazy-pagination. If you would like to help with this project see our Contributing doc for more info.
The app is available as open source under the terms of the MIT License.