Training Grounds
Search Result Shows the Previous QueryBlue Belt
+25 Ki
Description

A search component shows results for whatever the user types, updating on every keystroke.

Anomaly

Type "a" - result shows "Results for: " (empty). Type "b" - result shows "Results for: a". Every result lags one keystroke behind. The display never catches up to what is currently in the input.

Constraint
Do not remove the setTimeout
Hint

The callback runs after `handleChange` returns - which variable still holds the value you typed?

Consult the SenseiOnly for those truly stuck · Flip to reveal

The callback runs after `handleChange` returns - which variable still holds the value you typed?

Practice 14 related drills →
Loading editor…
Correct Solution
Loading...

Why this fixes it

The `setTimeout` callback closed over `query` from the render in which `handleChange` was called - but `setQuery(val)` does not update `query` synchronously, so by the time the callback ran, `query` still held the previous render's value. Replacing `query` inside the callback with `val` - the local variable captured from `e.target.value` before the timeout was scheduled - gives the closure a value that is already correct and does not depend on state having flushed.

Expected OutputGoal State
Your OutputLive