Created
June 30, 2024 13:12
-
-
Save carefree-ladka/2b8a2c8617bbe289f8ba312a537661c2 to your computer and use it in GitHub Desktop.
Infinite Scrolling in React.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { useState, useEffect } from 'react'; | |
| const InfiniteScroll = () => { | |
| const [data, setData] = useState([]); | |
| const [page, setPage] = useState(1); // Track current page | |
| const [loading, setLoading] = useState(false); // Track loading state | |
| const fetchData = async () => { | |
| setLoading(true); // Set loading state | |
| try { | |
| // Replace with your API endpoint | |
| const response = await fetch(`https://api.example.com/data?page=${page}`); | |
| const newData = await response.json(); | |
| setData(prevData => [...prevData, ...newData]); // Append new data to existing data | |
| setPage(prevPage => prevPage + 1); // Increment page count | |
| } catch (error) { | |
| console.error('Error fetching data:', error); | |
| } finally { | |
| setLoading(false); // Reset loading state | |
| } | |
| }; | |
| useEffect(() => { | |
| fetchData(); // Initial data fetch | |
| }, []); // Runs once after initial render | |
| const handleScroll = () => { | |
| if ( | |
| window.innerHeight + document.documentElement.scrollTop !== | |
| document.documentElement.offsetHeight || loading | |
| ) | |
| return; | |
| fetchData(); | |
| }; | |
| useEffect(() => { | |
| window.addEventListener('scroll', handleScroll); | |
| return () => window.removeEventListener('scroll', handleScroll); | |
| }, []); // Add and remove scroll event listener | |
| return ( | |
| <div> | |
| <ul> | |
| {data.map(item => ( | |
| <li key={item.id}>{item.title}</li> | |
| ))} | |
| </ul> | |
| {loading && <p>Loading...</p>} | |
| </div> | |
| ); | |
| }; | |
| export default InfiniteScroll; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment