To fetch data when a user scrolls to the bottom of a page in React, you can use the IntersectionObserver
API. Here's how you can implement it:
Create a reference to the element that you want to observe for intersection, usually the container that holds your data.
javascriptconst containerRef = useRef(null);
Create a state variable to keep track of whether or not you've reached the end of your data. This can be useful to prevent unnecessary API calls.
javascriptconst [reachedEnd, setReachedEnd] = useState(false);
Create an
IntersectionObserver
instance that will watch for when the container comes into view.javascriptuseEffect(() => { const options = { root: null, rootMargin: '0px', threshold: 1.0, }; const observer = new IntersectionObserver((entries) => { const [entry] = entries; if (entry.isIntersecting && !reachedEnd) { // Fetch more data here } }, options); if (containerRef.current) { observer.observe(containerRef.current); } return () => { observer.disconnect(); }; }, [containerRef, reachedEnd]);
When you fetch more data, update your state to indicate whether or not you've reached the end.
javascriptconst fetchMoreData = async () => { const newData = await fetchData(); if (newData.length === 0) { setReachedEnd(true); } else { setData((prevData) => [...prevData, ...newData]); } };
In this example, the IntersectionObserver
will trigger the fetchMoreData
function when the container comes into view and you haven't reached the end of your data. The fetchMoreData
function will fetch more data and update your state accordingly.
Remember to add a loading indicator to indicate that more data is being fetched, and handle any errors that may occur during the API request.