Reputation: 15
I made a search function. I get the data back in the console.log. Now I want to make sure that when I search something it also filters into the table. i use React-hooks.
function search (searchTerm) {
const search = getValues("products").filter(
product =>
product.description.toLowerCase().indexOf(searchTerm) > -1,
);
console.log(search);
}
Upvotes: 1
Views: 8642
Reputation: 2918
You're doing right but not setting the filteredProducts
in state
Considering this is your component
const YourComponent = (props) => {
const [filteredProducts, setFilteredProducts] = useState([]);
const [searchValue, setSearchValue] = useState('');
// your search event handler
function search (searchTerm) {
// update search value
setSearchValue(searchTerm);
const filtered = getValues("products").filter(
product =>
product.description.toLowerCase().indexOf(searchTerm) > -1,
);
// set filtered products in state
setFilteredProducts(filtered);
}
return (
<div>
{searchValue ? (
// loop over filtered products, so only searched products are shown
): (
// loop over products
)}
</div>
);
}
Upvotes: 2