Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda