wasAsked.

Build a React search component. There is a text input bound to React state (controlled). When the user types, wait 400ms after they stop typing, then call GET /api/employees?q=term. Rules: if the trimmed query length is less than 2, do not call the API — clear results and show nothing or a hint 'Type at least 2 characters'. While a request is in flight show 'Searching…'. If the user types again before the previous request finishes, ignore or abort the old response so an older slow response cannot overwrite newer results. On error show a friendly message. Please implement this with hooks only

PwC · Full Stack Developer · technical

Published

Year not specified · React

Community answers

Posted by wasAsked editorial collection

import { useEffect, useState } from 'react'; type Employee = { id: number; name: string; department: string }; export function EmployeeSearch() { const [query, setQuery] = useState(''); const [results, setResults] = useState<Employee[]>([]); const [status, setStatus] = useState<'idle' | 'loading' | 'done' | 'error'>('idle'); useEffect(() => { const term = query.trim(); if (term.length < 2) { setResults([]); setStatus('idle'); return; // no API call for short input } const controller = new AbortController(); const timer = setTimeout(async () => { setStatus('loading'); try { const res = await fetch(`/api/employees?q=${encodeURIComponent(term)}`, { signal: controller.signal }); if (!res.ok) throw new Error(`HTTP ${res.status}`); const data: Employee[] = await res.json(); setResults(data); setStatus('done'); } catch (err) { if ((err as Error).name === 'AbortError') return; // superseded by newer input setResults([]); setStatus('error'); } }, 400); // Runs when query changes or the component unmounts: // cancels the pending debounce AND aborts any in-flight request. return () => { clearTimeout(timer); controller.abort(); }; }, [query]); const tooShort = query.trim().length > 0 && query.trim().length < 2; return ( <div> <label htmlFor="employee-search">Search employees</label> <input id="employee-search" type="search" value={query} onChange={e => setQuery(e.target.value)} aria-describedby="search-status" autoComplete="off" /> <p id="search-status" role="status" aria-live="polite"> {tooShort && 'Type at least 2 characters'} {status === 'loading' && 'Searching…'} {status === 'error' && 'Something went wrong while searching. Please try again.'} {status === 'done' && results.length === 0 && 'No employees found.'} </p> <ul> {results.map(e => ( <li key={e.id}>{e.name} — {e.department}</li> ))} </ul> </div> ); } How it meets each rule - Controlled input: value and onChange bound to state. - Debounce: setTimeout of 400 ms inside useEffect; the cleanup clears the timer whenever the user types again, so only the last pause triggers a request. - Minimum length: trimmed queries shorter than 2 characters clear results and never call the API, with a hint shown. - Loading state: "Searching…" while the request is in flight. - Race conditions: each effect run has its own AbortController. When the query changes, the cleanup aborts the previous request, so a slow older response can never overwrite newer results; AbortError is ignored. - Errors: non-2xx responses and network failures show a friendly message. - Accessibility: a label, and a polite live region announcing status changes for screen readers. Possible extensions: extract a reusable useDebouncedValue hook, cache results per term, or use TanStack Query (with the debounced term as the query key), which handles cancellation and caching automatically.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics