Bruno Cicerchia
Bruno Cicerchia

Reputation: 37

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

Upvotes: 1

Views: 81

Answers (2)

Alp &#214;zaslan
Alp &#214;zaslan

Reputation: 91

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]);

Upvotes: 3

Nokwiw
Nokwiw

Reputation: 396

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;

Upvotes: 0

Related Questions