Reputation: 61
I am fetching an array of objects and I want to apply multiple filters. Following the scenario: Open popover and selected "cat" should show all the cats after pressing "APPLY", close the popover -> come back to filters -> "dog" is checked -> select and filter AGAIN by type "cat" AND by name "foxy" -> show all the cats with name "foxy". Seems like the data fetch from begin is not keeped in memory. Yes, because when I filter it, I set it by filters, but don't know how to refilter it.
Can you guide me and explain me how to do it? Thanks!
https://codesandbox.io/s/keep-data-after-i-apply-first-filter-f0cdj
Upvotes: 0
Views: 561
Reputation: 5868
You can use conditions in Array.filter
:
const handleFilteredData = () => {
setData(creaturesData.filter(c=>filters.type.includes(c.type) || filters.name.includes(c.name)))
};
But you have to pass the name of types to filters instead of ID:
const handleTypeCheck = (e) => {
const id = e.target.name;
console.log(typeof id);
const updatedData = data.map((item) => {
return item.type === id ? { ...item, checked: !item.checked } : item;
});
setData(updatedData);
};
Upvotes: 1