Infinite scroll pagination

Hi!

At the moment I have a page listing out blog articles and another blog details page.

The guides I have followed is

For the blog overall:

And the pagination from here:

The articles is retrieved using custom code from the pagination code. Now I want to implement a infinity autoloading of new articles when scrolling down. I have came so far that it at least triggers the observer when scrolling down but now Im stuck on how to actually trigger for example the “nextPage” function that is a server function.

Any good way to solve this in Builder?

Thanks!

async function main() {
  if (Builder.isBrowser) {
    setTimeout(() => {
      const loader = document.getElementById('LoadMoreArticles');

      const loadMorePosts = (entries, observer) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            // How to proceed here, if possible?
            console.log('Load more articles...');
          }
        });
      };

      const observer = new IntersectionObserver(loadMorePosts, {
        root: null,
        rootMargin: '0px',
        threshold: 1.0
      });

      observer.observe(loader);
    }, 1500);
  }

  if (Builder.isServer) {
    const POSTS_CONTENT_API_URL = "https://cdn.builder.io/api/v3/content/blog-article?apiKey=<API_KEY>&limit=16";

    state.offset = 0;
    state.blogArticlesResult = [];

    async function fetchArticles(offset) {
      try {
        const targetUrl = `${POSTS_CONTENT_API_URL}&offset=${offset}`;
        const response = await fetch(targetUrl);
        if (response.ok) {
          const data = await response.json();

          if (data.results.length === 0) {
            console.warn('No data found for offset:', offset);
            return null;
          }

          return data;
        } else {
          console.error('Failed to fetch articles');
          return null;
        }
      } catch (error) {
        console.error('Error fetching articles:', error);
        return null;
      }
    }

    function loadArticles() {
      fetchArticles(state.offset)
        .then((data) => {
          if (data) {
            state.blogArticlesResult = data;
            window.scrollTo(0, 0);
          }
        })
        .catch((error) => {
          console.error('Error loading articles:', error);
        });
    }

    function nextPage() {
      state.offset += 16;
      loadArticles();
    }

    function prevPage() {
      if (state.offset >= 16) {
        state.offset -= 16;
        loadArticles();
      }
    }

    state.loadArticles = loadArticles;
    state.nextPage = nextPage;
    state.prevPage = prevPage;

    loadArticles();
  }
}

export default main();

Hello @eklukris,

Welcome to the builder.io forum.

For me to be able to help you, could you please provide me with the Builder Content Entry link where you’re experiencing this issue?

Here is how to find it: