Live search
Code ReviewMiddle
- Target
- find the 2 must-fix problems (4 in all)
- Your best
- Not played yet
Pull request
Search as you type · feature/live-search
The search box no longer loads the whole catalog: it asks the server on every change of the query, and a label says how fresh the results are.
api.js: newsearchProducts(query).ProductSearch.jsx: searches when the query changes; an "Updated N s ago" label.
Checked by typing a few product names. Your teammate wrote it with an AI assistant and asks for a review before it is merged: comment on every line that has to change, and give each comment a category.
Hints
Your comments
Scoring: a comment finds a problem when it is on the problem's lines (or one line around them) and names its category. The score is the share of problems found, minus half a problem for each comment that finds nothing new. Find every must-fix problem, with no more such comments than there are problems, to complete the challenge. Only your first review is scored.
11import { useState } from "react";
22import { listProducts } from "./api.js";
11import { useEffect, useState } from "react";
22import { searchProducts } from "./api.js";
333
444export function ProductSearch() {
55 const [products, setProducts] = useState([]);
55 const [results, setResults] = useState([]);
666 const [query, setQuery] = useState("");
77 const [error, setError] = useState(null);
77 const [loading, setLoading] = useState(false);
88 const [updatedAt, setUpdatedAt] = useState(null);
99 const [now, setNow] = useState(() => Date.now());
81010
99 // Load the whole catalog on click, then filter it here.
1010 async function load() {
1111 try {
1212 setProducts(await listProducts());
1313 } catch (e) {
1414 setError(e.message);
1111 // Ask the server on every change of the query.
1212 useEffect(() => {
1313 if (query.trim() === "") {
1414 setResults([]);
1515 return;
151616 }
1616 }
1717 setLoading(true);
1818 searchProducts(query).then((items) => {
1919 setResults(items);
2020 setUpdatedAt(Date.now());
2121 setLoading(false);
2222 });
2323 }, [query]);
172424
1818 const shown = products.filter((p) => p.name.toLowerCase().includes(query.toLowerCase()));
2525 // Tick once a second for the "Updated N s ago" label.
2626 useEffect(() => {
2727 setInterval(() => setNow(Date.now()), 1000);
2828 }, []);
192929
203030 return (
213131 <section>
2222 <button onClick={load}>Load products</button>
233232 <label>
243333 Search
253434 <input value={query} onChange={(e) => setQuery(e.target.value)} />
263535 </label>
2727 {error && <p role="alert">{error}</p>}
3636 {loading && <p>Loading...</p>}
3737 {updatedAt && <p>Updated {Math.round((now - updatedAt) / 1000)} s ago</p>}
283838 <ul>
2929 {shown.map((p) => (
3939 {results.map((p) => (
304040 <li key={p.id}>{p.name}</li>
314141 ))}
324242 </ul>
3 unchanged lines