Blog>
Snippets

Implementing a Dynamic Loading Indicator for Data Fetching

Demonstrate integrating a dynamic loading indicator which appears as the user scrolls, signaling more data is being fetched in the context of virtual scrolling.
let isLoading = false;
Flag to keep track of loading state to avoid multiple fetch calls at the same time.
const fetchData = async () => {
  if (!isLoading) {
    isLoading = true;
    // Simulate fetching data
    setTimeout(() => {
      console.log('Data fetched');
      isLoading = false;
    }, 1000);
  }
};
Function to fetch data. It simulates a data fetching operation and logs a message once the data is fetched.
const observer = new IntersectionObserver(entries => {
  if (entries[0].isIntersecting) {
    console.log('Approaching end of list, loading more items.');
    fetchData();
  }
}, { threshold: 1.0 });
IntersectionObserver setup to trigger data fetching as the user scrolls close to the end of the list.
const listEnd = document.querySelector('#list-end');
observer.observe(listEnd);
Select the list end marker and start observing it with IntersectionObserver for scrolling near the end of the list.