npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-cursor-pagination

v0.0.2

Published

A React hook for cursor-based pagination with GraphQL

Downloads

2

Readme

usePagination Hook

The usePagination hook simplifies the process of adding pagination to your React components. It is designed to be used within a <PaginationProvider> context.

Installation

npm install use-cursor-pagination

Usage

First, wrap your component tree with :

import { PaginationProvider } from 'use-cursor-pagination';

function App() {
    return (
        <PaginationProvider>
            {/* Your components that use usePagination */}
        </PaginationProvider>
    );
}

Using with Apollo

import { useQuery } from '@apollo/client';
import { usePagination } from 'use-cursor-pagination';

const GET_ITEMS = gql`
  query GetItems($cursor: String, $limit: Int) {
    items(after: $cursor, first: $limit) {
      edges {
        node {
          id
          name
        }
      }
      pageInfo {
        endCursor
        hasNextPage
        hasPreviousPage
      }
      totalCount
    }
  }
`;

function ItemsList() {
  const { usePaginationEffect, getPaginationVariables } = usePagination();

  const { data: itemsData, loading: isItemsLoading } = useQuery(GET_ITEMS, {
    variables: {
      ...getPaginationVariables('itemsList'),
    },
    skip: !getPaginationVariables('itemsList')?.first && !getPaginationVariables('itemsList')?.last,
  });

  usePaginationEffect({
    dataKey: 'itemsList',
    hasNextPage: Boolean(itemsData?.items?.pageInfo.hasNextPage),
    hasPreviousPage: Boolean(itemsData?.items?.pageInfo.hasPreviousPage),
    initItemsPerPage: 10, // Set the initial number of items per page
    totalCount: itemsData?.items?.totalCount,
    endCursor: itemsData?.items?.pageInfo?.endCursor,
    startCursor: itemsData?.items?.pageInfo?.startCursor,
  });
}

The usePaginationEffect is a crucial part of the pagination system when working with GraphQL because it ensures that the pagination context is kept in sync with the latest data fetched from the server. Here's why it's important:

  1. Synchronization with Server Data: As your application fetches new data from the server, usePaginationEffect updates the pagination context with the most recent information, such as cursors and page availability (hasNextPage/hasPreviousPage). This ensures that the pagination controls reflect the actual state of your data.

  2. Cursor Management: GraphQL uses cursors to navigate through a dataset. usePaginationEffect handles the cursors (startCursor and endCursor) provided by the server, allowing the client to request the next or previous set of data accurately.

  3. Dynamic Pagination: The effect dynamically adjusts the pagination based on the total count of items (totalCount) and the initial number of items per page (initItemsPerPage). This allows for flexible and user-friendly pagination.

  4. Data Isolation with dataKey: The dataKey parameter is used to uniquely identify each pagination instance. This is important because it allows usePaginationEffect to manage multiple sets of paginated data independently within the same application. Each dataKey corresponds to a specific query, ensuring that the pagination controls interact with the correct dataset.

In summary, usePaginationEffect is essential for maintaining an up-to-date and accurate pagination state that corresponds with the data fetched from GraphQL queries. The dataKey is equally important as it isolates pagination states across different data sets or queries, preventing any mix-ups in the pagination logic.

Using pagination handles

To interact with the pagination handles in your component, you will use the functions provided by the usePagination hook. Here's a breakdown of each function and how to use it:

  • goFirstPage(dataKey): Navigates to the first page of the dataset.
  • goPreviousPage(dataKey): Moves to the previous page.
  • goNextPage(dataKey): Advances to the next page.
  • goLastPage(dataKey): Jumps to the last page.
  • setCountPerPage(dataKey, count): Sets the number of items to display per page.

The getPaginationEntry function is part of the usePagination hook's API. It retrieves the current state of pagination for a given data set identified by dataKey. The state includes several variables that are essential for managing pagination:

  • hasNextPage: A boolean that indicates whether there are more pages available after the current page.
  • hasPreviousPage: A boolean that shows if there are pages available before the current page.
  • currentPage: The number of the current page being displayed.
  • pagesAmount: The total number of pages available.

Here is an example of how these functions can be used in a component

import React from 'react';
import { usePagination } from 'use-cursor-pagination';

export const SimplePagination = ({ dataKey }) => {
  const {
    getPaginationEntry,
    setCountPerPage,
    goPreviousPage,
    goNextPage,
    goFirstPage,
    goLastPage
  } = usePagination();

  const { hasNextPage, hasPreviousPage, currentPage, pagesAmount } = getPaginationEntry(dataKey);

  return (
    <div>
      <div>
        <button onClick={() => goFirstPage(dataKey)} disabled={!hasPreviousPage}>
          First Page
        </button>
        <button onClick={() => goPreviousPage(dataKey)} disabled={!hasPreviousPage}>
          Previous Page
        </button>
        <span>Page {currentPage} of {pagesAmount}</span>
        <button onClick={() => goNextPage(dataKey)} disabled={!hasNextPage}>
          Next Page
        </button>
        <button onClick={() => goLastPage(dataKey)} disabled={!hasNextPage}>
          Last Page
        </button>
      </div>
      <div>
        <label>Items per page:</label>
        <select onChange={(e) => setCountPerPage(dataKey, Number(e.target.value))}>
          <option value="10">10</option>
          <option value="20">20</option>
          <option value="50">50</option>
        </select>
      </div>
    </div>
  );
};