I am trying to fetch all pictures from a Firebase storage.
The fetching works fine with the function _loadImages, but the fetched images are not shown.
I have the same issue with React and React Native.
I am trying since days but it just doesn't re-render the images.
Anyone an idea how I can re-render the fetched images?
import React, { Component } from 'react';
import Firebase from '../functions/Firebase'
class Images extends Component {
constructor(props) {
super(props)
Firebase.init();
this.state = {
imageUrl: "",
imageArray: [
"https://images.unsplash.com/photo-1571831284707-b14ca2e0da5f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
"https://images.unsplash.com/photo-1494537176433-7a3c4ef2046f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
"https://images.unsplash.com/photo-1579170130266-b77007d32ab5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
"https://images.unsplash.com/photo-1565047946982-5ca5149ce14c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
],
loading: false,
}
}
_loadImages = () => {
const imageArray = []
var storage = Firebase.storage
var storageRef = storage.ref()
var listRef = storageRef.child("images/")
listRef.listAll().then((res) => {
res.items.map((itemRef) => {
var urlFB = itemRef.name
var getPictureURL = 'images/'.concat(urlFB)
var starsRef = storageRef.child(getPictureURL)
starsRef.getDownloadURL().then((url) => {
imageArray.push(url)
})
})
})
this.setState({ imageArray })
}
_localLoadImages = () => {
this.setState({ loading: true })
this._loadImages()
this.setState({ loading: false })
}
handleUpload = (e) => {
e.preventDefault();
}
render() {
let imageUrlArray = this.state.imageArray
const images = imageUrlArray.map((item, i) => {
return (
<img
className="SingleImage"
src={item}
key={item}></img>
)
})
return (
<div className="Images" >
{images}
<button type='button' onClick={() => this._localLoadImages()}>Load Images!</button>
</div >
);
}
}
You are setting it to the state before the asynchronous function is done executing.
_loadImages = () => {
const imageArray = []
var storage = Firebase.storage
var storageRef = storage.ref()
var listRef = storageRef.child("images/")
listRef.listAll().then((res) => {
res.items.map((itemRef) => {
var urlFB = itemRef.name
var getPictureURL = 'images/'.concat(urlFB)
var starsRef = storageRef.child(getPictureURL)
starsRef.getDownloadURL().then((url) => {
imageArray.push(url)
this.setState({ imageArray })
})
})
})
}
Or with async/await
,
_loadImages = async () => {
const imageArray = []
const storage = Firebase.storage
const storageRef = storage.ref()
const listRef = storageRef.child("images/")
const list = await listRef.listAll();
list.items.map((itemRef) => {
var urlFB = itemRef.name
var getPictureURL = 'images/' + urlFB;
var starsRef = storageRef.child(getPictureURL)
const url = starsRef.getDownloadURL();
imageArray.push(url);
});
this.setState({ imageArray });
}