Home > OS >  Async Function Adding Elements Twice to an Array in React
Async Function Adding Elements Twice to an Array in React

Time:04-18

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

CodePudding user response:

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])]);
});
...
  • Related