Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

State not updating properly

I’m trying to get some images from my firebase storage like this:

const [images, setImages] = useState([]);

  useEffect(() => {
    function list() {
      const storage = getStorage();
      const imagesRef = ref(storage, "test/");

      listAll(imagesRef)
        .then((res) => {
          res.items.forEach((item) => {
            getDownloadURL(item).then((url) => setImages([...images, url]));
          });
        })
        .catch((error) => {
          console.error(error);
        });
    }
    list();
  }, []);

console.log(images);

As you can see I’m trying to get an array with all the images that are found in the storage.

The code seems to work, I’m not getting any errors but my state isn’t updating properly. I’m expecting something like [imageUrl1, imageUrl2, ...] but the logs are showing only one image url at the time:
Log screenshot

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

...images will not work when looping like this. The last image will be the only one written to the state. Instead, get a list of all the images first, then call setImages(images).

Promise.all can come in handy for this.

Promise.all(res.items.map(item => getDownloadURL(item))).then(images => setImages(images))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading