Start learning free

LESSON 131 OF 161 · FRONTEND: FRONTEND WITH AI

The AI Shows the Wrong Search in JavaScript

Practice

An AI assistant wrote the Corner Shop's search box. Every time the query changes, its effect asks the API and shows the answer:

useEffect(() => {
  async function search() {
    const response = await fetch("/api/products?q=" + encodeURIComponent(query));
    const data = await response.json();
    setResults(data);
  }
  search();
}, [query]);

Typing "mug" sends three requests: q=m, q=mu and q=mug. The network doesn't promise that answers come back in order. If the answer for m arrives last, it overwrites the one for mug: the field says "mug", but the list shows Mug $12 and Lamp $29. This is a race.

The fix: give each run of the effect its own flag, and let the effect's cleanup set it when the query changes. An answer whose flag is set is old, so you drop it. On a product page that loads by id, it could look like this:

useEffect(() => {
  let ignore = false;
  fetch("/api/products/" + id)
    .then((response) => response.json())
    .then((data) => {
      if (!ignore) setProduct(data);
    });
  return () => {
    ignore = true;
  };
}, [id]);

The check opens the page, then answers newer requests first while it types "mug":

> open the page             →  8 products, Mug $12 to Gift card $50
> from now on, later requests are answered first
> type "mug" into "Search"   →  answers for q=mug, then q=mu, then q=m
                               the list shows only Mug $12

Your task: in src/Search.jsx, add an ignore flag to the effect, set it to true in the effect's cleanup, and return early before setResults when it is set.


Assignment
Follow the Coding Tutorial to make the AI's search drop the answers of old queries, so the list always matches what is in the field.


Hint
The search and the cleanup of the same run share the same ignore. Check it after the answer has arrived, right before setResults.


STEP 1 OF 4
    Ctrl + Enter to check

    Aiui Race 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