I am implementing a React shopping cart, and I am having a locked loop problem with an useEffect hook.
Initially, I use an useEffect to fetch id's and quantities of products in the cart and store these values in a state variable array of objects named shopCart:
// fetches the id's and quantities of all products in the user's shopping cart
// and assigns these values to the shopCart array
// Each value of the shopCart array should be an object like this: {id:random_id, quantity:number_of_products }]
useEffect(() => {
let auxCart = []; // auxiliary array that will receive the result of the fetch request
// postData: performs a POST request with {userId:userId} as the body of the request
postData('REQUEST1_URL', { userId: userId })
.then(data => {
for (let i = 0; i < data.shopCart.length; i++) {
auxCart[i] = {};
auxCart[i].id = data.shopCart[i].id; //this shopCart is not the same shopCart state variable. Just a value received from the database
auxCart[i].quantity = data.shopCart[i].quantity;
}
});
setShopCart(auxCart);
}, [])
After that, I modify shopCart by adding attributes/keys with info about the products, such as product title, price and images:
// Modifies shopCart, which should contain only id's and quantities at the moment,
// assigning details to each product such as price and title.
// Each value of shopCart should be an object like this:
// {id:random_id, quantity:number_of_products,
// title:product_name, price:product_price,
// oldPrice:old_product_price, image:array_of_images,
// type:type_of_product}
useEffect(() => {
console.log('useEffect2');
if (!isFirstRender) { //Ref hook variable used to test if the useEffect is in the first render or not
let aux = [...shopCart]; // creates a copy of shopCart
for (let i = 0; i < shopCart.length; i++) {
// fetches the details of each product
fetch('REQUEST2_URL').
then(res => res.json()).
then(res => {
aux[i].image = res[0].image;
aux[i].title = res[0].title;
aux[i].price = res[0].price;
aux[i].oldPrice = res[0].oldPrice;
aux[i].type = res[0].type;
});
}
setShopCart(aux);
}
}, [shopCart]);
The problem is that the second useEffect keeps printing 'useEffect2' multiple times, showing that it is in a locked loop. How can I fix that ? I was expecting that, since the fetched products info doesn't change, the second useEffect would not be repeating everytime, but it does. I use shopCart in its dependecies arrays to wait for the first request to finish updating shopCart.