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-component-infinite-scroll

v1.1.3

Published

Create the effect of the infinite scroll using debounce effect and fetch fresh records once a user scrolls down to the bottom

Downloads

478

Readme

useInfiniteScroll Hook

useInfiniteScroll is a custom React hook that simplifies the implementation of infinite scrolling functionality in React applications. This hook utilizes Axios for fetching data and Lodash's debounce method to efficiently manage API request frequency. It is designed to be flexible, supporting both authenticated and unauthenticated requests, which makes it suitable for a wide range of API scenarios.

Features

  • Infinite Scrolling: Automatically loads new data as the user scrolls, improving user experience in content-heavy applications
  • Debounced API Requests: Uses Lodash's debounce to control the rate of API requests, which helps in reducing the number of calls made to the server under rapid scroll conditions and also have the functionality of search (if it is supporting by your API)
  • Flexible API Request Configuration: Can handle custom headers and authentication tokens, accommdating both public and secured APIs
  • Pagination and Error handling: Manages pagniation seamlessly and provides build-in error handling.

Installation

To use useInfiniteScroll, make sure you have axios and lodash installed in your porject. If not, install them using npm:

npm install axios lodash

After installing axios and lodash. Install the package by using this command (typescript version should be >4.0.5 & <5.0.0

npm install use-component-infinite-scroll

if you have some other version of typescript. You can install the package using this command

npm install use-component-infinite-scroll --legacy-peer-deps

Usage

Below is the basic example to demonstrate how to use the useInfiniteScroll hook in a React Component

import React, { useEffect } from 'react'
import { useInfiniteScroll } from  'use-component-infinite-scroll';

const App = () => {
  const fetchUrl = "https://api.example.com/data"

  const { listRef, data, loading, error, handleScroll } = useInfiniteScroll({
    url: fetchUrl,
    limit: 10,
    dependency: "id" // like the id  of parent record or any other dependency (optional)
    authToken: "your_auth_token", // optional
    headers: { "Custom-Header": "value" }, // optional
  });

  // IMP, this is to trigger the hook to fetch the record
  useEffect(() => {
   fetchData("", fetchUrl)
  }, [fetchUrl, fetchData])

  // This function is to handle the API search functionality and lodash (default delay time is 500 millisecond)
  const handleSearch = (value: string) => {
    fetchData(value, fetchUrl)
  };

  return (
    <div ref={listRef} onScroll={handleScroll}>
      {data.map((item, index) => (
        <div key={index}>{item.title}</div>
      ))}
      {loading && <p>Loading more items...</p>}
      {error && <p>{error}</p>}
    </div>
  );
}

Hook Props

The useInfiniteScroll hook accepts the following properties

| Property | Type | Description | Default | |---------------|--------|------------------------------------------------------------|---------| | url | string | The URL of the API endpoint. | | | limit | number | Number of items to fetch per page. | 10 | | initialData | array | Initial data to populate the list. | [] | | dependency | any | Dependency for re-triggering the data fetch. | | | searchQuery | string | Query parameter to pass with the API request for searching | | | debounceDelay | number | Time in milliseconds for debounce. | 500 | | authToken | string | Authorization token for making authenticated requests. | | | headers | object | Custom headers to send with the API request. | {} |

Return Values

The hook returns an bject containing the following:

  • listRef (React ref): Reference to the scrolling container.
  • data (array): The data fetched from the API.
  • loading (boolean): Indicates whether the data is currently being fetched.
  • error (string|null): Error message if an error occurred during fetching.
  • handleScroll (function): Function to call on scroll to fetch more data.

Contributing

Contributions are warmly welcomed! Please feel free to submit pull requests or create issues for any bugs and feature requests.

License

This project is licensed under the MIT License