简体   繁体   中英

Image is fetched from firebase storage but src value is unable to set in react ANTD Avatar component

I am using Avatar antd component. My image is fetched from the Firebase storage.

Here is the code which I already implemented.

  test = (imageName) => {
    if (imageName)
    {
        firebaseConfig.storage().ref().child(`users/${imageName}`).getDownloadURL().then(url => {
            return url;
        })
    }
    else{
        return "https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png";
    }
}

Here imagename will be considered as child name as you can see in the code.

Now, I will show you How I call that function from the class component.

 <Avatar src={this.test(imagename)} />

It is working fine if imagename is null.

Would you please help me to do so as I am new for React and Firebase.

The problem is that when imageName is not null, you use a promise to fetch the url from firebase. This means that an asynchronous operation will start (calling firebase for the url), and when it finishes the function you passed to the then will be called with the url that was found.

The problem is that returning from inside the promise doesn't return it from the function (since the function already returns while the asynchronous operation goes on in the background.

The solution in react for this problem would be to use state to store the url, and update it from within the then when the promise resolves.

In that case you will call the test function on the component mount, and instead of returning the url, it will set it to the state .

test = (imageName) => {
    if (imageName)
    {
        firebaseConfig.storage().ref().child(`users/${imageName}`).getDownloadURL().then(url => {
            this.setState({imageUrl: url});
        })
    }
    else{
       this.setState({imageUrl: "https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png"});
    }
}

Then you can use it from the state like this:

 <Avatar src={this.state.imageUrl} />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM