How would you build an accessible, async autocomplete?
Implement a production-minded autocomplete with async results, keyboard navigation, race protection, and correct combobox semantics.
Useful prerequisites
An autocomplete combines a text input with a changing list of suggestions. It looks small, but keyboard focus, screen-reader announcements, pointer selection and asynchronous results all have to agree about which option is active. The challenge is to make the interaction predictable without taking control away from the browser or assistive technology.
An autocomplete combines a text input with a changing list of suggestions. It looks small, but keyboard focus, screen-reader announcements, pointer selection and asynchronous results all have to agree about which option is active. The challenge is to make the interaction predictable without taking control away from the browser or assistive technology.
The quick version
Treat autocomplete as a small interaction system, not an input with a dropdown glued on. Keep four pieces of state independent: the text the user is editing, the actual selected value, which option is active for keyboard navigation, and the in-flight request. Implement the WAI-ARIA combobox pattern properly, support the expected keyboard model, and make sure only the latest request can update the results.
Implementation prompt
Build a reusable autocomplete for selecting a customer from a remote directory.
Functional requirements
- Support both controlled and clearly documented uncontrolled usage.
- Debounce the network request while the user is typing.
- Show distinct loading, results, empty, and error states.
- Handle Arrow Down/Up, Enter, Escape, and normal text editing.
- Allow pointer selection without fighting focus behaviour.
- Close the popup at the right times and surface the selected value to the parent.
Correctness and accessibility requirements
- Follow the WAI-ARIA combobox / listbox / option pattern.
- Keep
aria-expanded,aria-controls, andaria-activedescendantin sync with reality. - Never let an older response overwrite results for a newer query.
- Do not treat a highlighted option as selected until the user commits it.
- Preserve IME composition and ordinary editing behaviour.
Build the mental model
There are at least four values that must stay independent:
- The text currently in the input (what the user is typing).
- The committed domain value (the customer that was actually selected).
- The active option index (for keyboard highlighting).
- The request state (idle / loading / success / empty / error).
Mixing them is the source of most autocomplete bugs. Arrow Down should move the highlight without changing the selected value. Escape should close the list without wiping the text the user has already typed. A slow response for an old query should never replace the results for the query the user is looking at now.
Debouncing only reduces how many requests you send. It does nothing about responses arriving out of order. You need both cancellation (AbortController) and a sequence token (or equivalent) so that only the latest request is allowed to update visible state.
Concrete implementation sketch
let requestSequence = 0;
let activeController: AbortController | undefined;
async function loadSuggestions(query: string) {
const sequence = ++requestSequence;
activeController?.abort();
if (!query.trim()) {
suggestions = [];
status = 'idle';
return;
}
const controller = new AbortController();
activeController = controller;
status = 'loading';
try {
const response = await fetch(`/api/customers?q=${encodeURIComponent(query)}`, {
signal: controller.signal,
});
if (!response.ok) throw new Error(`Suggestion request failed: ${response.status}`);
const payload: unknown = await response.json();
const parsed = parseCustomerSuggestions(payload);
// Stale response — ignore it
if (sequence !== requestSequence || controller.signal.aborted) return;
suggestions = parsed;
status = parsed.length === 0 ? 'empty' : 'success';
} catch (error) {
if (controller.signal.aborted) return;
if (sequence !== requestSequence) return;
status = 'error';
// surface the error to whatever error reporting you use
}
}
A few production details that are easy to miss:
- Debounce the call to
loadSuggestions, not the abort logic inside it. - Clear any pending debounce timer on unmount or when the component is disabled.
- Treat an expected abort as normal control flow, not as an application error.
- Validate the response at the boundary. A TypeScript type assertion is not runtime validation.
Where it gets tricky
IME composition.
While the user is composing (common with Chinese, Japanese, Korean keyboards), intermediate composition strings should not fire requests or commit values. Listen to compositionstart / compositionend and ignore input events that are part of an ongoing composition.
Pointer selection vs blur.
If the input blurs before the option’s click handler runs, the popup can disappear and the selection is lost. The usual fix is to select on pointerdown (or mousedown) rather than click, or to keep the popup open until the selection is committed. Arbitrary setTimeout hacks are fragile.
Active option becomes invalid.
When new results arrive, the previously active index may now point at a different item or beyond the end of the list. Reset or clamp the active index when the result set changes.
Duplicate labels, distinct IDs.
Users select by identity, not by display string. If two customers can have the same name, the option must carry a stable ID and the selected value must use that ID.
Empty query, slow network, server error.
All three need explicit UI states. A spinner that never resolves and a silent failure are both worse than a clear empty or error message.
Keyboard + screen reader agreement.
aria-activedescendant must point at a real option that exists in the DOM. The option needs an ID. When the active option changes, the screen reader should hear the new option. This is easy to get wrong when results are virtualised or when the list is re-rendered.
A common misunderstandings
-
“If it works with a mouse it is accessible.”
Keyboard and screen reader behaviour are part of the contract. A mouse-only dropdown is not an autocomplete. -
“Adding
role="combobox"is enough.”
The role is only the start. Expanded state, controls relationship, active descendant, option roles, and keyboard handling all have to agree. -
“Debounce solves race conditions.”
Debounce only limits how often you send requests. Responses can still arrive out of order.
What this changes in an application
Autocomplete is a compact example of real frontend systems work. You have asynchronous consistency, cancellation, state modelling, keyboard interaction, accessible semantics, and trust-boundary validation all in one control. A weak implementation can select the wrong record, lose typed text, announce stale options, or become unusable without a pointer.
Teams that treat it as “just a dropdown with search” usually rediscover these problems in production, often after the component is already widely used.
Questions worth exploring next
- How would you extend this to multi-select with tokens?
- How would you handle tens of thousands of possible options without rendering every result?
- What should happen if the selected customer is deleted on the server after selection?
- How would you test the race between a slow response and a newer query?
References and next steps
- WAI-ARIA Authoring Practices — Combobox — the keyboard and accessibility behaviour you should match.
- Playwright network mocking — deterministic tests for request ordering and failures.