skip to Main Content

I’m using firebase storage to store some images, however, when I want to set the source of an <img> element to the corresponding URL, it just works on some images. This is the function I’m trying to implement:

function setImgUrl (element, imgPath) {
    getDownloadURL(refStorage(storage, imgPath))
    .then((url) => {
        element.src = url;
    })
}

I’ve found through the debugger that both the element and the image url are getting correctly passed to the .then(), but when it tries to set the source it just doesn’t work. I’ve tried both with element.src = url and element.setAttribute(‘src’, url), but the result is the same. The images on which it doesn’t work seem to be random even though when I reload the page they are the same.

2

Answers


  1. try to add a random string to the image that will force it to reload

    const randomString = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
          element.src = url + `?v=${randomString}`;
    
    Login or Signup to reply.
  2. Is the url of type string? You can test this with

    function setImgUrl (element, imgPath) {
        getDownloadURL(refStorage(storage, imgPath))
        .then((url) => {
            console.log(typeof url); // ---> Check if "string" appears in console
            // Also you can try:
            element.setAttribute('src', url);
        })
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search