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

93
Visualizações
Problem displaying an item according to the url - React

I have a question. I have a component that when entering /category/:categoryId is rendered doing a fecth to "api url + categoryId". My problem is that if I change from one category to another the page only changes if the useEffect is executed infinitely which generates problems to the view as seen below. How can I make it run once and when I change from /category/1 to /category/2 the useEffect is executed correctly?

const Categories = () => {
    let [producto, productos] = useState([]);
    const { categoryId } = useParams();

    useEffect(() => {
        fetch('https://fakestoreapi.com/products/category/' + categoryId)
            .then(res=>res.json())
            .then(data=>productos(data))
    },[]);

    console.log(producto)

    return(
        <div className="container">
            {producto.map((p) => (
                <Producto
                    title={p.title}
                    price={p.price}
                    description={p.description}
                    image={p.image}
                    key={p.id}
                    id={p.id}
                />
            ))}
        </div>
    )
}

export default Categories;

My router file:

<Route path="/category/:categoryId" component={Categories} />

This is the problem that is generated, there comes a time when a fetch is made to a previously requested category and then the new requested category is executed.

See my problem in video

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can simply add categoryId to useEffect array argument. Function inside the useEffect is called, only when categoryId changes

    useEffect(() => {
        fetch('https://fakestoreapi.com/products/category/' + categoryId)
            .then(res=>res.json())
            .then(data=>productos(data))
    },[categoryId]);
about 4 years ago · Juan Pablo Isaza Relatório

0

you can not edit producto directly, you should use productos :

const Categories = () => {
    let [producto, productos] = useState([]);
    const { categoryId } = useParams();

    useEffect(() => {
        fetch('https://fakestoreapi.com/products/category/' + categoryId)
            .then(res=>res.json())
            .then(data=>productos(data))
    },[]);

    console.log(producto)

    return(
        <div className="container">
            {producto && producto.map((p) => (
                <Producto
                    title={p.title}
                    price={p.price}
                    description={p.description}
                    image={p.image}
                    key={p.id}
                    id={p.id}
                />
            ))}
        </div>
    )
}

export default Categories;
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