Start learning free

LESSON 9 OF 58 · FULL-STACK: TWO PROGRAMS, ONE APP

Pages of Products

Practice

A real shop can have thousands of products, so the server sends them in pages. The page asks for one page with ?page=1&per_page=3, and the given server answers an object: items, the products of that page; total, how many products match in all; and next_page, the page to ask for next, or null on the last one.

The footer can then tell the visitor where they are: Showing the number of products on the screen of the total. A Load more button asks for the next page and adds its items after the ones already shown. In React you build a new array with both, using spread:

const seen = ["Mon", "Tue"];
const more = ["Wed"];
const days = [...seen, ...more]; // ["Mon", "Tue", "Wed"]

After each page, keep its next_page: the next click must ask for that page. When it is null, nothing is left, and the button goes away.

Your page must do this (3 products per page, 8 in the shop, 4 of them with an "e" in the name):

open the page      →  GET /api/products?q=&page=1&per_page=3   →  Mug, Notebook, Lamp · Showing 3 of 8 · Load more
click "Load more"  →  GET /api/products?q=&page=2&per_page=3   →  + Pen, Plant, Teapot · Showing 6 of 8
click "Load more"  →  GET /api/products?q=&page=3&per_page=3   →  + Stapler, Gift card · Showing 8 of 8 · no Load more
search "e"         →  GET /api/products?q=e&page=1&per_page=3  →  Notebook, Pen, Teapot · Showing 3 of 4 · Load more

GET /api/products?q=e&page=2&per_page=3  →  200  {"items": [{"id": 7, "name": "Stapler", "price": 9, "stock": 15}], "next_page": null, "total": 4}

Your task: in client/src/pages/ProductsPage.jsx, keep total and nextPage in state and fill them from the first page's answer, show Showing … of … in the footer, and add a Load more button whose loadMore function appends the next page.


Assignment
Follow the Coding Tutorial to show the products a page at a time: the count from total, and a Load more button that appends the next page.


Hint
loadMore asks the same address as the effect, with nextPage in place of 1. Update nextPage after every click, or each click asks for page 2 again.


STEP 1 OF 12
    Ctrl + Enter to check