Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

136
Visualizações
How to filter array to match params value with react

I wanted to create a e-commerce web application using react-bootstrap. I want the page to show different item based on category so if the URL is product/men'sclothing i want to filter my array and show only the product that have same category which is men's clothing (my path: product/:category). I already tried to filter my array using .filter method but it didn't work, it still show all product from various category, How can I fix it ?

Categorized product page:

const ProductList = () => {
  const { category } = useParams()
  const[productList, setProductList]= useState();

  useEffect(() =>{
    axios.get(`https://fakestoreapi.com/products`).then(res => {
        const products = res.data;
        setProductList(products);

        var filteredCategory =
         productList.filter((productList) =>productList.category === {category})
      })
  }, []);

  console.log(productList)

  return (
    <>
      <Row>
        <h1> This is {category} paged</h1>
        {productList && productList.map(product =>{
          const {id, title, price, category,description,image} = product;
          return(
          <Col lg={3} className="d-flex">
            <Card key={id} className="flex-fill productlist">
              <Card.Img variant="top" src={image} />
              <Card.Body>
                <Card.Title>{title}</Card.Title>
                <Card.Text>{category}</Card.Text>
                <Card.Text>
                  Current Price: {price}
                </Card.Text>
                <Button variant="primary">Add to cart</Button>
              </Card.Body>
            </Card>
          </Col>
          )
        })}
      </Row>
    </>
  )
}

export default ProductList
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

In the filter function that you have used, try writing it as

productList.filter((product) => product.category === category)
  1. When you write it as {category}, a object is created with key category and the value as the actual value. For example if value of category is shoes, it will create a object, { category: "shoes" }.
  2. You also need to add category in useEffect dependency, to re-fetch products every time category is updated.
about 4 years ago · Juan Pablo Isaza Relatório

0

Try getting rid of the {} around the category variable in the filter function. The filter function is not inside the return statement and thus plain js (not jsx).

Also, you're never using the array containing the filtered products. I'd suggest to filter the products you get from axios, take the filtered products and put THEM into state with setProductList.

Was not able to test this since I'm on mobile, but give it a try.

about 4 years ago · Juan Pablo Isaza Relatório

0

First, add a dependency to your UseEffect then remove the bracket inside the filter.

useEffect(() => {
  async function getByCategory(){
   const req = await fetch(URL):
   const res = await req.json();
   const filter = res.filter((item) => item.category === category);
   setProductList(filter);
  }
  // check if params exits
  if(category){
      getByCategory();
  }
}, [category]);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda