Start learning free

LESSON 53 OF 161 · FRONTEND: TALKING TO AN API

Send a Search in JavaScript

Practice

The shop's API can filter for you. You tell it what you want in the query string, the part of the URL after the ?: pairs of name=value, joined by &. For example /api/products?q=mug&category=kitchen asks for the kitchen products whose name matches "mug".

In app.js, the fetch line at the top of try in loadProducts was taken out: you write it again with the query string. Until then, try uses a response that doesn't exist, so your page starts with "Can't reach the shop", Try again and 0 products.

Don't glue the pairs together by hand: a space or an & inside a value would break the URL. A URLSearchParams collects the pairs with set and writes them out correctly encoded when you join it to a string. With no pairs, it writes nothing. For example, to ask for the products sorted by price:

const params = new URLSearchParams();
params.set("sort", "price");
fetch("/api/products?" + params);   // asks /api/products?sort=price

index.html now has a Search box and a Category select. Send only what the visitor chose: an empty box sends no q, and the option All, whose value is "", sends no category. To ask again on every change, listen for the box's input event and the select's change event.

The check picks Kitchen, types "mug", empties the box, then picks All. Your page must ask:

> open the page
  request: GET /api/products -> 200                        8 products
> choose "Kitchen" in "Category"
  request: GET /api/products?category=kitchen -> 200       2 products
> type "mug" into "Search"
  request: GET /api/products?q=m&category=kitchen -> 200
  request: GET /api/products?q=mu&category=kitchen -> 200
  request: GET /api/products?q=mug&category=kitchen -> 200   1 products
> type "" into "Search"
  request: GET /api/products?category=kitchen -> 200       2 products
> choose "All" in "Category"
  request: GET /api/products -> 200                        8 products

Your task: in loadProducts, build a URLSearchParams with q and category when they are not empty, fetch "/api/products?" plus it, and call loadProducts on every input of the box and every change of the select.


Assignment
Follow the Coding Tutorial to send the search box and the category to the API as a query string, and to ask again whenever either one changes.


Hint
An empty string counts as false, so if (search.value) runs only when the box has text. Joined to a string, an empty URLSearchParams adds nothing after the ?.


STEP 1 OF 9
    Ctrl + Enter to check

    Fetch Query String 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