0

I'm trying to map array to get image url from Firebase storage and list them to page. The code give me a url, but the problem is that code not set url to img variable on time and returning empty img variable.

return(
    <div>
        <Header />
        {this.state.loaded ? <Loading /> : null}
        <div>
            {this.state.productsArr.map((product, i) => {
                let img = '';
                storageRef.child(`images/${product.images[0]}`)
                                        .getDownloadURL()
                                        .then((url) => {
                                            img = url
                                            console.log('then img', img)
                                        })
                                        .catch((err) => console.log(err))
                console.log('result',img)

                return(
                    <div key={i}>
                        <div>
                            <div>
                                <img src={img}
                                    alt={product.category} 
                                />
                            </div>
                        </div>
                    </div>
                )
            })}
        </div>
        <Footer />
    </div>
)

Where I did mistake? Also get results twice.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Romanas
  • 547
  • 7
  • 25

1 Answers1

1

Calling getDownloadURL() means that the SDK has to call to the server to get that URL. By the time that call returns from the server with the download URL, the <img src={img} has long since run.

For this reason you'll want to store the download URL in the state, and then use the URL from the state in your render method.

You'll typically start loading the data in your componentWillMount method:

componentWillMount() {
    let promises = this.state.productsArr.map((product, i) => {
        return storageRef.child(`images/${product.images[0]}`).getDownloadURL();
    });
    Promise.all(promises).then((downloadURLs) => {
        setState({ downloadURLs });
    });
}

When you call setState() React will automatically rerender the UI parts that are dependent on the modified state. So then in your rendering method you'd use the download URLs from state.downloadURLs.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • thanks Frank for your answer, I think your solution is correct but I just wonder is there solution that works directly in component render – Romanas Apr 14 '20 at 05:11