The search field now fills query, but the list under it is empty: no cards, no count. The list you want isn't new data: it is products seen through query. So don't keep it in a second state. Compute it while the component draws. Each key calls setQuery, React calls ProductList again, and the filtered list is worked out fresh from the new query.
filter makes a new array with the items whose function returns true, and leaves the original alone. For example, a price limit kept in state:
const [maxPrice, setMaxPrice] = useState(10);
const cheap = products.filter((product) => {
return product.price <= maxPrice;
});
With maxPrice at 10, cheap holds Notebook, Pen and Stapler, and {cheap.length} is 3. If cheap were its own state, every change to maxPrice would have to update it too, and one forgotten place leaves the page out of step. To match names in any case, lowercase both sides: "Notebook".includes("n") is false, but "notebook".includes("n") is true.
The check types into Search and must see:
> open the page
text: 8 products (all 8 cards)
> type "n" into "Search"
text: 3 products Notebook, Pen, Plant
> type "pl" into "Search"
text: 2 products Plant, Stapler
> click "Clear"
text: 8 products (all 8 cards again)
Your task: in src/ProductList.jsx, compute shown from products and query with filter, show {shown.length} products under the search box, and draw the list from shown.
Assignment
Follow the Coding Tutorial to filter the products by the search query during the draw, with no second state.
Hint
Lowercase both the product's name and the query before includes, so n also finds Notebook. The list's map runs over shown, not products.
Free plan: 30 tutor messages. PRO is unlimited.
