Ionic adding infinite scroll to our list

— 5 minute read

permalink

Yesterday we created an API powered list in Ionic, but let's see how we can add an infinite scroll to it.

Infinite scrolls are proven to be very good on mobile phones. I think they have an addicting pattern in them.

You as a person are not forced to load a new page, and the timeline becomes endless.

A goto example would, of course, be Facebook or Instagram, but many more use this Principle.

Today we will be making an infinite loading list in Ionic, that will work as you can see in the screenshot below.

Ionic infinite loading

High-level overview permalink

In a high-level overview, it comes down to old-school pagination.

Once we hit a certain scroll amount (almost at the bottom), we fire an event that will fetch our new results from the API.

In the meantime, we keep track of paging and how many results we can still load.

In the demo API that we are using our endpoint returns a result like this.

{
"page": 1,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 1,
"name": "cerulean",
"year": 2000,
"color": "#98B2D1",
"pantone_value": "15-4020"
},
// Other data
]
}

We see there are two pages in total, so we can use our infinite loading once.

Enough to demo it out to you guys.

Adding the infinite scroll permalink

Our starting point for this tutorial is the end result of yesterday. You can find the code on GitHub.

Now, let's start by adding the infinite loading component to our tab1.page.html.

<ion-infinite-scroll threshold="100px" (ionInfinite)="loadData($event)">
<ion-infinite-scroll-content
loadingSpinner="bubbles"
loadingText="Loading more data...">

</ion-infinite-scroll-content>
</ion-infinite-scroll>

So this piece of code will call the loadData call, but that call is not ready to load paginated results.

Let's make some adjustments to tab1.page.ts.

First let's add a page number variable.

page: number = 1;

Now we can modify our loadData method.

loadData(event = null) {
this.http
.get<{ data: any[] }>(`https://reqres.in/api/unknown?page=${this.page}`)
.subscribe((resp: { data: any; total_pages: number }) => {
if (this.page !== resp.total_pages) {
this.page++;
} else {
if (event) event.target.disabled = true;
}
this.data = this.data.concat(resp.data);
if (event) event.target.complete();
});
}

We are now calling the API with page parameters, on the response we check if this page is the last page.

Then we add one to our page counter. Else we disable the infinite load since we are done.

Else we concat the existing data with this new data. And tell the infinite loading this call is done.

There we go!

Ionic infinite loading list data from an API.

You can find this project code on GitHub.

Thank you for reading, and let's connect! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter