Blog>
Snippets

Handling Scroll Events to Trigger Data Fetching

Provide an example of adding an event listener to the scroll event in a React component to trigger data fetching when the user scrolls to a certain point.
import { useEffect } from 'react';

function ScrollComponent({ fetchNextPage, hasNextPage }) {
  useEffect(() => {
    const handleScroll = () => {
      const nearBottom = window.innerHeight + window.scrollY >= document.body.offsetHeight - 100;
      if (nearBottom && hasNextPage) {
        fetchNextPage();
      }
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, [fetchNextPage, hasNextPage]);

  return (
    <div>
      {/* Content here */}
    </div>
  );
}
This code adds an event listener to the 'scroll' event of the window object. Inside the 'handleScroll' function, it checks if the user has scrolled near to the bottom of the page. If the user is near the bottom and there are more pages to fetch ('hasNextPage' is true), it will call the 'fetchNextPage' function to fetch the next chunk of data. This is used for implementing infinite scrolling in a React component, where 'fetchNextPage' is a function provided by React Query's 'useInfiniteQuery' hook.