'how to filter with two condition in react.js
I'm trying to create an e-commerce website using react-bootstrap and for my product detail page I want to show the product based on the item chosen by the user which have different id and category. I want to filter so it only show the item that have the same id and category, but it didn't work it still show all of the item only based on their category. I want it to be based on category and id. How can I fix that ?
my Code:
const ProductList = () => {
const { category, id } = useParams()
const[productList, setProductList]= useState();
useEffect(() =>{
axios.get(`https://fakestoreapi.com/products`).then(res => {
const products = res.data;
var filteredCategory =
products.filter((productList) =>
productList.category === category || productList.id === id)
setProductList(filteredCategory)
})
}, []);
console.log()
return (
<>
<Container fluid>
{productList && productList.map(product =>{
const {id, title, price, category,image} = product;
return(
<Row>
<Col lg={3} className="d-flex">
<img src={image} width="50%"></img>
</Col>
<Col>
<h1> {title}</h1>
</Col>
</Row>
)
})}
</Container>
</>
)
}
Solution 1:[1]
product id from the API response is number type and id extracted from useParams is string type. You can ignore the type when comparing using == instead of ===. And if you meant to filter with both conditions met then it should be && instead of ||.
Instead of
productList.category === category || productList.id === id
Try
productList.category === category && productList.id == id
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
