Start learning free

LESSON 101 OF 161 · FRONTEND: REACT ROUTES AND SHARED STATE

Filters in the Address in JavaScript

Practice

Filters kept in useState live only in the open page. A reload starts the page fresh and they are gone, and a link you send to a friend shows the full list. The fix is to keep them in the address, after the ?: /?q=mug&category=kitchen. These search params are name=value pairs joined by &.

React Router's useSearchParams works like useState, but its value is the address. searchParams.get("name") reads one param, or gives null when the address has none. setSearchParams writes a new address as a new entry in the history, so Back undoes it. For example, an orders page could keep its page number in the address:

const [searchParams, setSearchParams] = useSearchParams();
const page = searchParams.get("page") || "1";

// a click on "Next" calls:
setSearchParams({ page: "2" });   // the address becomes /orders?page=2

An effect with the params in its dependencies loads the list again each time the address changes: after a filter, after Back, after a reload.

The check filters by Kitchen, searches for mug, presses Back and reloads:

> click "Filter"   (Category: Kitchen)
  request: GET /api/products?category=kitchen -> 200
> the address bar
  /?category=kitchen
> press Enter   (Search: mug)
  request: GET /api/products?q=mug&category=kitchen -> 200
> the address bar
  /?q=mug&category=kitchen
> press the browser's Back button
  request: GET /api/products?category=kitchen -> 200
> the address bar
  /?category=kitchen
> reload the page
  request: GET /api/products?category=kitchen -> 200
  item: Mug $12
  item: Teapot $22

Your task: in src/ProductsPage.jsx, read q and category from useSearchParams, give them and setSearchParams to the given Filters form, and load the products in an effect that runs again when q or category change.


Assignment
Follow the Coding Tutorial to move the shop's filters into the address with useSearchParams, so a reload, a shared link and the Back button all show the right list.


Hint
searchParams.get("q") gives null when the address has no q, so add || "". The effect's dependencies are [q, category].


STEP 1 OF 9
    Ctrl + Enter to check

    Route Search Params 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