Bruce Mathers
Bruce Mathers

Reputation: 681

displaying all images from firebase storage (react native)

I can get it to display one image but go into a folder and display all images. I feel like my mapping is wrong.

From my understand .child() refers to a name of the file but from my understanding it can also refer to the folder that you want to access and listAll() tell it to list all of the files that is the file.

    const [sampleImage, setSampleImage] = useState(); 

    const getSampleImage = async () => {
        const imageRef = firebase.storage().ref().child('Front/').listAll();
        const url = await imageRef.getDownloadURL().catch((error) => { throw error });
        setSampleImage(url);
    }

 
    useEffect(() => {
        getSampleImage();
    });


  return (
        { sampleImage && getSampleImage.map(Image => (
                <View style={{ justifyContent: 'center' }} key={imageRef.id}>
                    <Image source={{ uri: sampleImage.get(k) }} style={{ width: 350, height: 350 }} /> 
                </View>
                ))}
    );
 }


Upvotes: 1

Views: 1649

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598708

The listAll() API returns a promise of a ListResult, which contains a list of StorageReference items, so you'll need to await the list, loop over that, and call getDownloadURL() on each.

Something like:

const getSampleImage = async () => {
    const imageRefs = await firebase.storage().ref().child('Front/').listAll();
    const urls = await Promise.all(imageRefs.items.map((ref) => ref.getDownloadURL());
    setSampleImage(urls);
}

And then:

{ sampleImage && getSampleImage().map(url => (
    <View style={{ justifyContent: 'center' }} key={imageRef.id}>
        <Image source={{ uri: url }} style={{ width: 350, height: 350 }} /> 
    </View>
))}

Upvotes: 4

Related Questions