I created a react product list using state and I also created a filter to filter the product. My problem is when I clicked on the category button the second time my page disappear.
I tried not to use state to store data in memory but did not work. A link to my sandbox code is here.
https://codesandbox.io/s/l1b3od?file=/src/styles.css&resolutionWidth=612&resolutionHeight=675
CodePudding user response:
You must change you filter function to this:
const Filtfunc = (prod)=>{
const result = Products.filter((x)=>{ // Here's the change
return x.category === prod
})
setData(result)
console.log(result)
}
You were filtering the data not the products, so once it's filtered the first time you have not all the products to filter, only the filtered data.
CodePudding user response:
In your filter
function you try to filter the Products
by using data
, but when you click to any category, you set the data
to be that array with result which can be also empty. You have to filter the array by using Products
, not the data
you set later on. Thus, it should be:
const Filtfunc = (prod) => {
const result = Products.filter((x) => {
return x.category === prod;
});
setData(result);
};
You can also set if
statement to check if your array returns anything or not:
<div className="create">
{data.length > 0 ? (
data.map((product) =>
// things here
)) : (
<h2>No result has been found</h2>
)}
</div>