Question presented to candidate: "Build a country field that suggests matches as the user types. Suggestions come from an API. The user should be able to pick one with the arrow keys and Enter, or with the mouse. Do not call the API for a query we already asked about."
Requirements:
- Fetch suggestions (at most 6, prefix matches first) about 250 ms after the user stops typing.
- Show a dropdown with Loading / No matches / suggestion states.
- Keyboard: Down / Up move the highlight and wrap around, Enter picks the highlighted suggestion, Escape closes.
- Mouse: hovering highlights, clicking picks, and the input keeps focus.
- Cache results per query so going back to an earlier query (for example with Backspace) does not hit the API again; ignore a response if a newer lookup has started.
- Show the picked value and a small counter of requests sent and cache hits. The API is simulated.
What a strong answer should cover:
- State model: input text, open flag, suggestions, active index, picked value; the active index reset whenever suggestions change.
- Debounce reused from a small hook / composable, and a lookup that only runs when the dropdown is open and the debounced value has caught up.
- A
Mapcache keyed by the normalised query, and a "latest request id" check so an older response cannot replace newer suggestions. - Keyboard handling on the input with wrap-around,
mousedownpreventDefaultso clicking an option does not blur the input, and closing on blur. - Basic combobox ARIA:
role="combobox",aria-expanded,aria-controls,aria-activedescendant,role="listbox"/role="option".
Clarifying questions expected:
- "Is the list small enough to filter on the client, or must every query go to the server?"
- "Should picking a suggestion only fill the input, or also navigate somewhere?"
- "How long may cached results be reused?"
Code / implementation expected: Yes. A working autocomplete with debounced fetching, a cache and full keyboard and mouse selection.