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

Async Function Adding Elements Twice to an Array in React

I have a React page that pulls images from a folder in firebase and then dynamically displays them inside of a div. Currently, when the website loads, the custom hook I wrote to pull in the images is called twice due to React StrictMode being enabled. The images are added twice because the functions are loading the images while the component remounts and the length of the images state array is still 0 at that point. I know removing StrictMode would solve this problem but I was wondering if there was a better solution.

import { useEffect, useRef, useState } from "react"
import { storage } from './Firebase'
import { getDownloadURL, listAll, ref } from 'firebase/storage'


const useImages = () => {
    const [loaded, setLoaded] = useState(false);
    const [images, setImages] = useState([]);

    useEffect(() => {
        const fetchImages = () => {
            const imageFolder = ref(storage, "images/");
            listAll(imageFolder).then((folderItems) => {
                folderItems.items.forEach((imageRef) => {
                    getDownloadURL(imageRef).then((imageLink) => {
                        setImages((prevImages) => [...prevImages, imageLink]);
                    });
                });
            });
        }

        if (!loaded) {
            setLoaded(true);
            fetchImages();
        }
        
    }, []);


    return images;
}


const Gallery = () => {
    const imageContainer = useRef(0);
    const images = useImages();

    // ON LOAD
    useEffect(() => {
        
    }, []);

    return (
        <div>
            <div ref={imageContainer}>
                {images.map((link) => 
                    <img width={200} src={link} />
                )}
            </div>
        </div>
    )
}


export default Gallery

>Solution :

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

You could try one of the following to prevent duplicates.

Preliminary check

...
getDownloadURL(imageRef).then((imageLink) => {
  if(images.indexOf(imageLink) !== -1) return;
  setImages((prevImages) => [...prevImages, imageLink]);
});
...

Set

...
getDownloadURL(imageRef).then((imageLink) => {
  setImages((prevImages) => [...new Set([...prevImages, imageLink])]);
});
...
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