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

118
Visualizações
img src doesn't load image through function

Fist of all, I made a sandbox: https://codesandbox.io/s/naughty-almeida-u66mlt?file=/src/App.js

The problem is that the requested image doesn't show when the function gets called and the url is returned.

What I have tried so far and the result:

  1. First I added the getDownloadURL() inside the querySnapshot.forEach and pushed the retrieved url to the paths array. It looked like this:

    useEffect(() => {
        const q = query(collection(db, "gallery"));
        const unsubscribe = onSnapshot(q, (querySnapshot) => {
          const path = [];
          querySnapshot.forEach((doc) => {
            getDownloadURL(ref(storage, doc.data().bild)).then((url) {
              path.push(doc.data(), url);
             })
          });
          console.log(path);
          setPaths(path);
        });
        setLoading(false);
        return unsubscribe;
      }, []);
    

    Then I mapped over paths but the image didn't show.

  2. I created another useState and called the function getURL(src) inside querySnapshot.forEach(). Inside the getURL() function I updated that state with the retrieved url from getDownloadURL(). Afterwards I added the state to src and it worked.

    But my concern is that, when there is more than one image it fails, I haven't tested it yet.

  3. I converted the retrieved url form getDownloadURL to a string. Like so

    function getURL(src) {...} return String(url) but that didn't work either.

The <img /> gets rendered with "alt" Text ,so I think it has something to do with url.

I don't understand the problem in general and I hope somebody can help me to fix it.

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

0

You can split you component into small ones. Let's say Gallery and GalleryImage.

GalleryImage will take src and description props. Declare a imageSrc state variable in this component. Then you can do your call in the useEffect (with src in the dependencies array) and then set the imageSrc state when the call is complete. Calling setImageSrc will trigger a re-render.

Updated sandbox : https://codesandbox.io/s/silly-fire-f84e95

about 4 years ago · Juan Pablo Isaza Relatório

0

Both loading data from Firestore, and getting a download URL for an image is an asynchronous operation. You're calling setPaths(path) before any of the calls to path.push(doc.data(), url) have happened.

I recommend running the code in a debugger, or adding logging, to verify this, as it is key to understanding how to deal with asynchronous APIs.

The solution is always the same: any code that needs data that is loaded asynchronously, needs to be inside the callback that gets called when that data is available.

So in your case, the simplest way to do that would be:

onSnapshot(q, (querySnapshot) => {
  const path = [];
  querySnapshot.forEach((doc) => {
    getDownloadURL(ref(storage, doc.data().bild)).then((url) {
      path.push(doc.data(), url);
      setPaths(path); // 👈
    })
  });
});

This sets the paths every time you get a download URL.


If you want to wait setting the paths until you got all download URLs, you can use a counter to check the number of documents vs the number of download URLs, or you can use promises and Promise.all:

onSnapshot(q, (querySnapshot) => {
  const promises = querySnapshot.docs.map((doc) => getDownloadURL(ref(storage, doc.data().bild)))
  Promise.all(promises).then((urls) {
    setPaths(urls);
  })
});
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