Start learning free

LESSON 84 OF 161 · FRONTEND: REACT EFFECTS AND DATA

Ask Again When Something Changes

Practice

An effect with [] runs once, after the first draw: right for loading the list when the page opens. Now the visitor picks a category in a menu, and the page must ask the API again, for that category only. The API filters with a query string: /api/products?category=kitchen.

In the starting code, the products' effect and its fetch have been taken out, so your page shows Loading products… forever. You will write them again, this time with [category].

The array after the effect's function holds its dependencies. After every draw, React compares each value in it with the value from the draw before, and runs the effect again when one changed. Put a value there when the effect must run again each time it changes:

useEffect(() => {
  loadOrder();
}, [orderId]);

Here, when orderId changes, the page loads that order; any other draw skips the effect. The menu itself is a controlled select: it shows a state value, and its onChange sets that state.

The check opens the page, chooses Kitchen, then All. Your page must print:

> open the page
  request: GET /api/products -> 200
  select "Category": "All" of [All, Home, Kitchen, Office]
  text: 8 products
> choose "Kitchen" in "Category"
  request: GET /api/products?category=kitchen -> 200
  text: 2 products   (Mug and Teapot)
> choose "All" in "Category"
  request: GET /api/products -> 200
  text: 8 products

Your task: in src/App.jsx, add a category state starting as "" and a labelled menu, Category, with the options All, Home, Kitchen and Office. In loadProducts, fetch the address with ?category= when a category is chosen, and call loadProducts from an effect that has [category] as its dependencies.


Assignment
Follow the Coding Tutorial to add the category menu and make the page load the products again each time the visitor chooses a category.


Hint
An empty string counts as false, so category ? … : … picks the plain /api/products when All is chosen. With [] instead of [category], the menu changes but the list never does.


STEP 1 OF 11
    Ctrl + Enter to check