JAVASCRIPT

Handling API Pagination with an Infinite Scroll or Load More Button

Implement efficient API pagination with infinite scrolling or a 'Load More' button in JavaScript. Fetch data incrementally to improve user experience for large datasets.

let currentPage = 1;
let isLoading = false;
let hasMoreData = true;

async function fetchPaginatedData(page) {
    if (isLoading || !hasMoreData) return;
    isLoading = true;
    console.log(`Fetching page ${page}...`);

    try {
        // Replace with your actual API endpoint and pagination parameters
        const response = await fetch(`https://api.example.com/items?page=${page}&limit=10`);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        
        // Assuming API returns an array of items and a 'has_next_page' flag or similar
        const newItems = data.items || [];
        hasMoreData = data.has_next_page || newItems.length > 0; // Adjust based on API response

        // Append newItems to your UI list (e.g., a <div> or <ul>)
        newItems.forEach(item => {
            const itemElement = document.createElement('div');
            itemElement.textContent = `Item ID: ${item.id}, Name: ${item.name}`;
            document.getElementById('content-container').appendChild(itemElement);
        });

        currentPage++;
        console.log(`Loaded ${newItems.length} items. Current page: ${currentPage}`);
        if (!hasMoreData) {
            console.log('No more data to load.');
        }
    } catch (error) {
        console.error('Error fetching paginated data:', error);
    } finally {
        isLoading = false;
    }
}

// --- Example Integration ---
// For a "Load More" button:
// document.getElementById('load-more-button').addEventListener('click', () => {
//     fetchPaginatedData(currentPage);
// });

// For infinite scroll (using Intersection Observer):
// const observerTarget = document.getElementById('observer-target'); // An empty div at the bottom of content
// const observer = new IntersectionObserver((entries) => {
//     if (entries[0].isIntersecting && !isLoading && hasMoreData) {
//         fetchPaginatedData(currentPage);
//     }
// }, { threshold: 0.5 });
// observer.observe(observerTarget);

// Initial load
// fetchPaginatedData(currentPage);
How it works: This snippet demonstrates how to handle API pagination for displaying large datasets, commonly seen in infinite scroll or 'Load More' patterns. It manages `currentPage`, `isLoading` state, and `hasMoreData` flags to control when new requests are made. The `fetchPaginatedData` function fetches data incrementally, appends it to the UI, and updates the pagination state, improving performance and user experience.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs