Start learning free

LESSON 151 OF 161 · FRONTEND: INTERVIEW QUESTIONS

Autocomplete

Practice

An autocomplete field suggests matches while the visitor types. Asking the server at every keystroke wastes requests. A good field waits until typing stops for a moment, and that is called a debounce. The network can also answer requests out of order, so the field must ignore a late answer for text the visitor has already changed.

In React, an effect can start a timer. The function the effect returns is its cleanup, and React runs it before it runs the effect again. In this example, a note's text goes into the tab's title only after 1 second with no changes:

useEffect(() => {
  const timer = setTimeout(() => {
    document.title = "Draft: " + note;
  }, 1000);
  return () => clearTimeout(timer);
}, [note]);

Each change of note cancels the old wait and starts a new one. The same cleanup can also set a flag, like ignore = true. The flag tells the old run to drop an answer that arrives after the text has changed.

The check types l, waits 200 ms and then types a. It also makes the network answer later requests first. Your page must show:

> open the page
      heading 1: Corner Shop
      field "Search products": ""
> from now on, later requests are answered first
> type "l" into "Search products"
> 200 ms pass
> type "a" into "Search products"
> 300 ms pass
  request: GET /api/products?q=la -> 200
    +   option: Lamp $29
    +   option: Plant $15
> press ArrowDown
> press ArrowDown
    +   option: Plant $15 (selected)
> press Enter
    -   option: Lamp $29
    -   option: Plant $15 (selected)
    +   text: You picked Plant.

Your task: in src/App.jsx, make the effect ask GET /api/products?q= with the text once typing has stopped for 300 ms. Put the matches in the list, ignore late answers, and make Enter pick the highlighted match.


Assignment
Follow the Coding Tutorial to debounce the search with a timer and a cleanup, drop late answers with an ignore flag, and pick a match with Enter.


Hint
The cleanup sees the old run's variables. Setting ignore or clearing timer there only affects the run for the old text.


STEP 1 OF 12
    Ctrl + Enter to check