Start learning free

LESSON 157 OF 161 · FRONTEND: INTERVIEW QUESTIONS

Load More

Practice

Many shops don't send every product at once. The page asks the shop API for one page of products, and a Load more button asks for the next page and adds it to the end of the list. When no more pages are left, the button goes and the page says so.

The shop API answers GET /api/products?page=1&per_page=3 with one page: {items, page, total, next_page}. items holds the page's products, and next_page is the page to ask for next, or null on the last page.

To add a page to the list, you build a new array with the spread ..., which lays out an array's items one by one:

const seen = ["Mug"];
const more = ["Pen", "Plant"];
const all = [...seen, ...more];
// ["Mug", "Pen", "Plant"]

While a page is on its way, the button is disabled, so a quick double-click can't ask for the same page twice. The check opens the page and clicks Load more twice. Part of what it must see:

> open the page
  request: GET /api/products?page=1&per_page=3 ...
    list "Products" (empty)
    footer
      button: Load more (disabled)
  answer: GET /api/products?page=1&per_page=3 -> 200
    +     item: Mug $12
    +     item: Notebook $7
    +     item: Lamp $29
    +     button: Load more
> click "Load more"
  request: GET /api/products?page=2&per_page=3 ...
    +     item: Pen $2
    +     item: Plant $15
    +     item: Teapot $22
> click "Load more"
  request: GET /api/products?page=3&per_page=3 -> 200
    +     item: Stapler $9
    +     item: Gift card $50
    -     button: Load more
    +     text: That's everything

Your task: in src/App.jsx, loadPage already asks for a page and reads the answer into data. Add the page's items to the list, keep next_page and a loading flag in state, and in the footer show the Load more button, or the text "That's everything" when no page is left.


Assignment
Follow the Coding Tutorial to show the Corner Shop's products 3 at a time, with a Load more button that adds the next page.


Hint
Use an updater function to add to the list: it gets the current products. Show the button with {nextPage !== null && …}. Write the apostrophe text as a string in curly braces.


STEP 1 OF 8
    Ctrl + Enter to check