Search code examples
imagereact-nativeamazon-s3aws-amplify

Can't show image from s3 in React Native using Amplify Storage API


I'm simply trying to show an image from an s3 bucket using AWS Amplify's storage and react native. My code is the following:

class App extends React.Component {

  state = { fileUrl: '' }

  componentDidMount() {
        Storage.get('vlad-tchompalov-450777-unsplash.jpg')
          .then(data => {
            console.log("data: ", data)
            this.setState({
              fileUrl: data
            })
          })
          .catch(err => {
            console.log("error fetching image", err)
          })
      }

  render() {
    return (
      <View style={styles.container}>
      { this.state.fileURL != '' && console.log('state: ', this.state.fileUrl) &&
        <Image source={{ uri: this.state.fileUrl }} style={{ width: 100, height: 100 }} />
      }
      </View>
    );
  }
}

From the console.log() I DO get the proper URL of the photo (if I click it I can see the photo) and it has https, so that shouldn't be the problem: console

I didn't add access level to the API call so it defaults to 'public' which is what I need.

I checked the configuration and permissions and seems to be OK.

Thanks!


Solution

  • console.log('state: ', this.state.fileUrl)
    

    always represents a falsy value, so

    <Image source={{ uri: this.state.fileUrl }} style={{ width: 100, height: 100 }} />
    

    will never be considered and added to the render method. Removing it will fix the bug. Simply like:

    { this.state.fileURL != '' && <Image ... /> }