I am using React-id-swiper to load images for products. Let's say I have 5 products.
I am trying to use a function to detect when every image is successfully loaded, then when they are, set the useState 'loading' to false, which will then display the images.
I am using a variable 'counter' to count how many images there are to load. Once 'counter' is more than or equal to the amount in the list (5), set 'loading' to FALSE and load the images.
However, I am noticing that when I console log 'counter' when running it from useEffect, it ends at '0' and renders 5 times. 'Loading' also remains true.
However, if I trigger a re-render, I see 1,2,3,4,5 in the console. 'Loading' then turns to false.
I suspect this is to do with useEffect being too fast, but I can't seem to figure it out. Can somebody help?
Code:
const { products } = useContext(WPContext);
const [productsList, setProductsList] = useState(products);
const [filteredList, setFilteredList] = useState(products);
const [loading, setLoading] = useState(false);
useEffect(() => {
loadImages(products);
}, []);
const loadImages = (allProducts) => {
let counter = 0;
setLoading(true);
const newProducts = allProducts.map((product) => {
const newImg = new Image();
newImg.src = "https://via.placeholder.com/450x630";
newImg.onload = function () {
counter += 1;
};
// At this point, if I console log 'counter', it returns as 0. If I trigger a re-render, it returns as 1,2,3,4,5
return {
...product,
acf: {
...product.acf,
product_image: {
...product.acf.product_image,
url: newImg.src,
},
},
};
});
handleLoading(newProducts, counter);
};
const handleLoading = (newProducts, counter) => {
if (counter >= filteredList.length) {
setLoading(false);
counter = 0;
setFilteredList(newProducts);
}
};
First weird thing is that you are calling the handleLoading() function before its even defined. This is probably not a problem but a weird practice.
You are also creating a new variable counter when you pass it in as an argument. You aren't actually reseting the counter that you want.
Also using onload is unnecessary and can cause weird behavior here since its not a synchronous operation but event based. As long as you set the img.src it should force it to load.
Try this:
const loadImages = (allProducts) => {
let counter = 0;
setLoading(true);
const newProducts = allProducts.map((product) => {
const newImg = new Image();
newImg.src = "https://via.placeholder.com/450x630";
counter += 1;
return { ...product, acf: { ...product.acf, product_image: { ...product.acf.product_image, url: newImg.src }}};
});
const handleLoading = (newProducts) => {
if (counter >= filteredList.length) {
setLoading(false);
counter = 0;
setFilteredList(newProducts);
}
};
handleLoading(newProducts);
};
useEffect(() => {
loadImages(products);
}, []);