Skip to main content
10

Autocomplete

Hardreactdebouncerace conditionsa11y

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

Build an autocomplete (typeahead) input for picking a country. api.js is a fake search server, and App.js shows the selected country under the input. Right now the input does nothing.

js
const countries = await searchCountries('ger', { signal })
// [{ code: 'DE', name: 'Germany' }, ...]

The API behaves like a real network: every response takes a random 100 to 800 ms, so responses can come back in a different order than you sent the requests. Searching for error always fails.

Requirements

  • As the user types, show up to 10 matching countries in a list under the input.
  • Debounce: only search after the user has stopped typing for 300 ms, not on every keystroke.
  • Race conditions: the list must always match the latest query. A slow response for an older query must never replace the results of a newer one.
  • An empty (or whitespace-only) query shows nothing and sends no request.
  • Show Searching... while loading, No countries match "…" when there are no results, and an error message when the request fails.
  • Clicking a suggestion, or pressing Enter on the highlighted one, puts its name in the input, closes the list and calls onSelect(country).
  • ArrowDown and ArrowUp move the highlight through the list, wrapping around at the ends. Escape closes the list.
  • The list closes when the input loses focus, but clicking a suggestion must still select it.

Accessibility

Follow the WAI-ARIA combobox pattern:

  • The input has role="combobox", aria-expanded, aria-controls pointing to the list and aria-autocomplete="list".
  • The list has role="listbox", and each suggestion has role="option" and aria-selected when highlighted.
  • Focus stays in the input. The highlighted option is announced through aria-activedescendant.

Note

The preview updates as you type. There are no automated tests for this challenge yet: type quickly, delete characters, try error, and use only the keyboard. Then compare with the reference solution.

Follow-ups interviewers ask

  • Highlight the part of each suggestion that matches the query.
  • Cache results so typing ger, then germ, then back to ger doesn't search for ger again.
  • What would you change for a list of 100,000 local items instead of a server?
  • How would you make it generic, e.g. <Autocomplete fetchSuggestions={...} renderItem={...} />?

The approach

Three problems sit on top of each other here, and each has its own tool:

ProblemTool
Don't search on every keystrokeA useDebouncedValue hook
Old responses overwriting new onesAbortController, aborted in the effect's cleanup
Keyboard and screen reader supportThe combobox pattern with aria-activedescendant

Debounce as a value, not a function

useDebouncedValue(query, 300) returns the query only once it has stopped changing for 300 ms. Each change restarts a setTimeout, and the effect's cleanup clears the previous one. The search effect then depends on the debounced value, so it runs once per pause in typing.

Debouncing a value is easier to get right in React than wrapping the fetch in a debounce() function. A debounced function has to survive re-renders (with useMemo or useRef) and has to be cancelled on unmount.

The race condition

Without protection, this happens:

Loading diagram...

The fix is in the effect's cleanup. React runs the cleanup of the previous effect before the next one, so every new query calls controller.abort() on the request for the previous query. An aborted request rejects with an AbortError, which the .catch ignores, and its results are never written to state. As a bonus, the browser cancels the actual network request.

If an API doesn't accept a signal, the same idea works with a flag: let ignore = false in the effect, ignore = true in the cleanup, and only setResults when !ignore.

Keyboard and focus

  • Focus stays in the input the whole time. activeIndex tracks the highlighted option, and aria-activedescendant tells screen readers which one it is. Moving real focus into the list would make typing impossible.
  • Arrow keys wrap with modulo: (index + step + length) % length.
  • event.preventDefault() on arrows stops the cursor from jumping to the start or end of the text.

The blur problem

Closing on blur is easy, but it breaks mouse selection: pressing the mouse button on an option blurs the input first, the list closes, and the click never lands on the option. The solution selects on mousedown and calls event.preventDefault() there, which stops the input from losing focus at all.

What interviewers look for

  • Debouncing, and handling the empty query.
  • Naming the race condition before being asked, and fixing it with AbortController or an ignore flag.
  • Loading, empty and error states.
  • The combobox ARIA pattern with aria-activedescendant.
  • The mousedown versus blur ordering problem.

Reference solution

src/Autocomplete.js

jsx
import { useEffect, useId, useState } from 'react'

import { searchCountries } from './api'

/** `value`, but only after it has stopped changing for `delay` ms. */
function useDebouncedValue(value, delay) {
  const [debounced, setDebounced] = useState(value)
  useEffect(() => {
    const timer = setTimeout(() => setDebounced(value), delay)
    return () => clearTimeout(timer)
  }, [value, delay])
  return debounced
}

export default function Autocomplete({ id, onSelect }) {
  const [query, setQuery] = useState('')
  const [results, setResults] = useState([])
  const [status, setStatus] = useState('idle') // 'idle' | 'loading' | 'success' | 'error'
  const [open, setOpen] = useState(false)
  const [activeIndex, setActiveIndex] = useState(-1)
  const debouncedQuery = useDebouncedValue(query.trim(), 300)
  const listId = useId()

  useEffect(() => {
    if (!debouncedQuery) {
      setResults([])
      setStatus('idle')
      return
    }
    // Every new query aborts the previous request, so a slow old response can
    // never overwrite the results of a newer query.
    const controller = new AbortController()
    setStatus('loading')
    searchCountries(debouncedQuery, { signal: controller.signal })
      .then((items) => {
        setResults(items)
        setActiveIndex(-1)
        setStatus('success')
      })
      .catch((error) => {
        if (error.name !== 'AbortError') setStatus('error')
      })
    return () => controller.abort()
  }, [debouncedQuery])

  const showList = open && status === 'success' && results.length > 0
  const optionId = (index) => `${listId}-option-${index}`

  function select(item) {
    setQuery(item.name)
    setOpen(false)
    onSelect(item)
  }

  function onKeyDown(event) {
    if (event.key === 'Escape') {
      setOpen(false)
      return
    }
    if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
      event.preventDefault()
      setOpen(true)
      if (results.length === 0) return
      const step = event.key === 'ArrowDown' ? 1 : -1
      setActiveIndex((index) => (index + step + results.length) % results.length)
      return
    }
    if (event.key === 'Enter' && showList && activeIndex >= 0) {
      event.preventDefault()
      select(results[activeIndex])
    }
  }

  return (
    <div className="autocomplete">
      <input
        id={id}
        className="input"
        placeholder="Start typing a country..."
        role="combobox"
        aria-autocomplete="list"
        aria-expanded={showList}
        aria-controls={listId}
        aria-activedescendant={showList && activeIndex >= 0 ? optionId(activeIndex) : undefined}
        autoComplete="off"
        value={query}
        onChange={(event) => {
          setQuery(event.target.value)
          setOpen(true)
        }}
        onFocus={() => setOpen(true)}
        onBlur={() => setOpen(false)}
        onKeyDown={onKeyDown}
      />
      <ul id={listId} className="listbox" role="listbox" hidden={!showList}>
        {results.map((item, index) => (
          <li
            key={item.code}
            id={optionId(index)}
            className="option"
            role="option"
            aria-selected={index === activeIndex}
            // mousedown, not click: preventDefault keeps focus in the input, so
            // its blur doesn't close the list before the click lands.
            onMouseDown={(event) => {
              event.preventDefault()
              select(item)
            }}
            onMouseEnter={() => setActiveIndex(index)}
          >
            {item.name}
          </li>
        ))}
      </ul>
      <div role="status">
        {open && status === 'loading' && <p className="message">Searching...</p>}
        {open && status === 'error' && (
          <p className="message error">Something went wrong. Try again.</p>
        )}
        {open && status === 'success' && results.length === 0 && (
          <p className="message">No countries match "{debouncedQuery}".</p>
        )}
      </div>
    </div>
  )
}