Add live user search
React · React · intermediate · greenfield
Adds live user search. The component fetches `/api/search` whenever the query changes and renders the matching users. Tested locally with several queries and the list updates correctly on every keystroke.
Used in the admin panel header. Production users often search from slow mobile networks.
Requirements
- Add a live search box.
- As the user types, show the results that match the current query.
- The displayed list must always correspond to the latest query the user typed.
Files touched
- src/components/UserSearch.jsx
--- src/components/UserSearch.jsx
+function UserSearch({ query }) {
+ const [results, setResults] = useState([]);
+ useEffect(() => {
+ fetch(`/api/search?q=${query}`)
+ .then((res) => res.json())
+ .then((data) => setResults(data));
+ }, [query]);
+ return (
+ <ul>{results.map((u) => <li key={u.id}>{u.name}</li>)}</ul>
+ );
+}