0

I'm trying to get images from my firebase storage, to create a portfolio. They are in different directories (one per country). For the moment, I get all the URLs, but my map is empty and I don't know how to refresh my functional component!

Here is some code:

//firebase.js        
export const getImages = (country) => {
        let images = [];
        firebase.storage().ref().child('Images/' + country).list().then(result => {
            // Loop over each item
            result.items.forEach(pics => {
                firebase.storage().ref().child(pics.fullPath).getDownloadURL().then((url) => {
                    console.log(url);
                    images = [...images, url]
                })
            });
            return images;
        })
    }
    
    export const getAllImages = () => {
        let allImages = [];
    
        allImages = [...allImages, getImages("France")];
        return allImages;
    }

My component:

import {getAllImages} from "../firebase/firebase.js";

function Gallery (props) {
    const country = props.country;
    const [data, setData] = useState([])
    
    useEffect( () => {
        let urls = getAllImages();
        console.log(urls);
        if (urls) {
            setData(urls);
        }
    },[country])

    const imagesRender = () => {
        if (data.length >= 1) {
            switch (country) {
                case 'France':
                    return (data[0].map((item, id) => (
                        <img key={id} src={item} alt=""/>
                    )));
                case 'Japan':
                    return (data[1].map((item, id) => (
                        <img key={id} src={item} alt=""/>
                    )));
                case 'South Korea':
                    return (data[2].map((item, id) => (
                        <img key={id} src={item} alt=""/>
                    )));
                default:
                    return (data.map((item, id) => (
                        <img key={id }src={item} alt=""/>
                    )));
            }
        }
    }

    return (
        <div className="col-8">
            <div>
                {imagesRender()}
            </div>
        </div>
    );
}

export default Gallery;
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Thorek
  • 11
  • 1
  • The `setData()` calls will need to happen after the `getDownloadURL` (and other asynchronous) calls complete. See https://stackoverflow.com/questions/48045366/retrieve-file-from-firebase-storage/48046146#48046146 and https://stackoverflow.com/questions/61988980/how-to-list-all-the-names-and-download-urls-from-firebase-using-react-js/61990652#61990652 for some examples of this. – Frank van Puffelen Oct 08 '20 at 16:46
  • Thanks, It's working ! – Thorek Oct 09 '20 at 10:16

0 Answers0