I have this situation with my code.
I currently have an Input to look the items up and and filter to sort by price. The problem is that I have to add the two variables in front of the .map to make them work:
objectsToShow.map
objectsToShow makes the filter work but if I change it to
displayPage.map
the displayPage makes the input work but the select doesn't work anymore
That means I have to add those two variables in fron of the .map
I try this but I doesn't work
Input and pagination code.
//***************INPUT SEARCH *************/
const [searchTerm, setSearchTerm] = useState("");
const searchedProduct = products.filter((item) => {
if (searchTerm.value === "") {
return item;
}
if (item.title.toLowerCase().includes(searchTerm.toLowerCase())) {
return item;
} else {
return console.log("not found");
}
});
const [pageNumber, setPageNumber] = useState(0);
const productPerPage = 12;
const visitedPage = pageNumber * productPerPage;
const displayPage = searchedProduct.slice(
visitedPage,
visitedPage + productPerPage
);
const pageCount = Math.ceil(searchedProduct.length / productPerPage);
const changePage = ({ selected }) => {
setPageNumber(selected);
};
Filtering
const [objectsToShow, setToShow] = React.useState(products)
const compare = (a, b, ascendingOrder) => {
if (a < b) {
return ascendingOrder ? -1 : 1;
}
if (a > b) {
return ascendingOrder ? 1 : -1;
}
return 0;
}
const handleChange = (value) => {
if(value == 'none'){
setToShow([...products])
} else {
let toType, toAscending
switch(value){
case 'ascending' : toType = true; toAscending = true; break;
case 'descending' : toType = true; toAscending = false; break;
case 'high' : toType = false; toAscending = true; break;
case 'low' : toType = false; toAscending = false; break;
}
let current = [...products]
current.sort((a, b) => toType ?
compare(a.name, b.name, toAscending)
:
compare(a.price, b.price, toAscending))
setToShow([...current])
}
}
I want to implement it right here:
{objectsToShow.map((item) => (
<Col lg="3" md="4" sm="6" xs="6" key={item.id} className="mb-4">
<ProductCard item={item}/>
</Col>
))}