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

157
Visualizações
function called from useEffect rendering too fast and breaks, works correctly after re-render

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);
    }
  };
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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);
}, []);
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