Skip to content

Bi-directional GraphQL React hook for use with Apollo's useLazyQuery.

License

Notifications You must be signed in to change notification settings

itzsaga/use-lazy-pagination

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@itzsaga/use-lazy-pagination

Greenkeeper badge npm version

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.

Installation

$ npm i @itzsaga/use-lazy-pagination

or

$ yarn add @itzsaga/use-lazy-pagination

Usage

The hook expects a single argument, the query function returned from the @apollo/react-hooks useLazyQuery hook.

const { goBack, goForward } = useLazyPagination(queryPosts);

Return

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.

Example

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>
  );
}

Contributing

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.

License

The app is available as open source under the terms of the MIT License.

About

Bi-directional GraphQL React hook for use with Apollo's useLazyQuery.

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published