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-fetch-on-scroll-hook

v1.0.3

Published

A custom hook for infinite scrolling in React.

Downloads

8

Readme

use-fetch-on-scroll-hook

A simple yet powerful hook to handle infinite scrolling in React. use-fetch-on-scroll-hook makes it easy to load more data as the user scrolls, either upwards or downwards. This hook simplifies the implementation and improves performance.

🚀 Install bash Copiar código npm install --save use-fetch-on-scroll-hook

or

yarn add use-fetch-on-scroll-hook

// In code ES6 import useFetchOnScroll from 'use-fetch-on-scroll-hook'; // Or CommonJS const useFetchOnScroll = require('use-fetch-on-scroll-hook').default; 📚 Usage

import { useEffect, useState } from 'react';
import axios, { AxiosResponse } from 'axios';
import { useFetchOnScroll } from 'use-fetch-on-scroll-hook';


export const Test = () => {

  const [isLoading, setIsLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [items, setItems] = useState<any[]>([]);

  const fetchData = async (): Promise<void> => {
    setIsLoading(true);

    try {
      const res: AxiosResponse<any> = await axios.get(
        'https://pokeapi.co/api/v2/pokemon',
        {
          params: {
            page: page,
          },
        },
      );

      if (page > 1) {
        setItems((prevItems) => [...prevItems, ...res.data.results]);
      } else {
        setItems(res.data.results);
        setPage(2)
      }

      if (items.length + res.data.results.length >= res.data.count) {
        setHasMore(false);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  //? you can be passing the "data" type if you want
  const { containerRef, handleScroll } = useFetchOnScroll<any>({
    page,
    setPage,
    hasMore,
    fetchMoreData: () => fetchData(),
    dependencyArray: [],
    data: items,
    fetchDirection: 'BOTTOM',
  });

  return (
    <div
      ref={containerRef}
      onScroll={handleScroll}
      style={{
        height: '300px',
        overflow: 'auto',
      }}
    >
      <div>
        {items &&
          items.map((i, index) => {
            return (
              <div key={i.external_id}>
                <div>{i.name}</div>
              </div>
            );
          })}
      </div>
      {isLoading && <p>Loading...</p>}
    </div>
  );
};

The useFetchOnScroll hook can be utilized in several ways:

Specify a fetchDirection to determine whether to load more content as the user scrolls up or down. Use scrollableTarget to attach the scroll behavior to a specific DOM element. Handle complex scroll scenarios like reverse scrolling for chat applications. 📜 Props Name Type Description fetchMoreData function Function to fetch more data when the user reaches the end of the scrollable area. It should trigger a state update to append new data. dependencyArray array Array of dependencies for triggering the scroll action (only use if necessary). Changes in these dependencies will refetch data. data array The data being scrolled through. Used to control scroll behavior and to append new items. fetchDirection string Scroll direction to fetch more data. Can be "TOP" or "BOTTOM". page number The current page number for pagination. setPage function Function to update the current page number. hasMore boolean Boolean indicating if more data is available to load. Contributors ✨ Thanks to these wonderful people (emoji key):

LICENSE MIT