use-filtered-results
v1.0.0
Published
Get filtered results from an array of objects
Downloads
2
Maintainers
Readme
useFilteredResults Hook
useFilteredHook is a very simple hook that will give you filtered results from an array of objects, using a normalised string filter and an array of keys by which to filter the data.
Install
npm i use-filtered-results
Usage
import { useEffect, useState } from "react";
import useFilteredResults from "useFilteredResults";
const ExampleComponent = (props) => {
const [results, setResults] = useState([]);
const [filter, setFilter] = useState("");
const [filtered] = useFilteredResults(results, filter, ["body", "name"]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/comments")
.then((response) => response.json())
.then(setResults);
}, []);
return (
<div>
<input
type="text"
name="filter"
value={filter}
onChange={(e) => setFilter(e.target.value)}
/>
<div>Results: {filtered.length}</div>
{filtered.map((result) => (
<>
<li key={result.id}>
{result.name} : {result.body}
</li>
</>
))}
</div>
);
}