Start learning free

LESSON 59 OF 161 · FRONTEND: TALKING TO AN API

Load More in JavaScript

Practice

A list can be too long to send at once. Many APIs answer it in pages: you say which page you want and how many items per page, and the answer says which page comes next.

Your page starts with 0 products: loadProducts reads the answer into data but no longer puts it into products. In step 2 you put it back, this time from the answer's items.

For example, a blog API could answer GET /api/posts?page=1&per_page=10 with {"items": [ …10 posts… ], "page": 1, "total": 25, "next_page": 2}. On the last page, next_page is null: there is nothing more to ask for.

A Load more button asks for next_page and adds its items after the ones already on the screen. When an answer's next_page is null, the button leaves the screen. The search and the category stay in every address; only the page changes.

Your page must do this:

open the page      →  GET /api/products?page=1&per_page=3  →  200   3 products, button: Load more
click "Load more"  →  GET /api/products?page=2&per_page=3  →  200   6 products
click "Load more"  →  GET /api/products?page=3&per_page=3  →  200   8 products, no Load more button

Your task: ask for 3 products per page, take the products from the answer's items, keep the answer's next_page in nextPage, hide the Load more button when it is null, and write loadMore, which adds the next page to the list.


Assignment
Follow the Coding Tutorial to load the products 3 at a time and make a Load more button that appends the next page until there is none.


Hint
Join the lists with concat: the old products first, then the new items. After every answer, copy its next_page into nextPage, or every click asks for the same page.


STEP 1 OF 12
    Ctrl + Enter to check

    Fetch Pages in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free