1

If loading the image fails then onError method is called. However it does not tell us the reason why it failed. Is there a way I could find out why RN could not load the image? Was it because of 404 or 500 or a user was not connected to the internet? etc

import React, { Component } from 'react';
import { View, Image } from 'react-native';

export default class DisplayAnImage extends Component {
  render() {
    return (
      <View>

        <Image
          style={{width: 50, height: 50}}
          onError={({ nativeEvent: {error} }) => {
              console.log(error) // < ---- How to get error code? 
          }

          source={{uri: 'https://reactnative.dev/img/tiny_logo.png'}}
        />

      </View>
    );
  }
}

Yahoo
  • 4,093
  • 17
  • 59
  • 85

1 Answers1

0

Simple Solution (but it's bad):

You can get the error message and check if the string includes a status code, example:

const errorMessage = "Failed to load resource https://reactnative.dev/img/random_image.png (404)"
errorMessage.includes("404")

Another Solution

Using Fetch.

fetch("https://reactnative.dev/img/random_image.png")
  .then((res) => {  
    // the request status in in res.status
    // res.status = 404 -> error
    // res.status = 200 -> success
  })
  .catch((e) => {})

Fetch promises only reject with a TypeError when a network error occurs.

I found some helpful links if you need:

React-Native check image url

Fetch: reject promise and catch the error if status is not OK?

Luan Eduardo
  • 406
  • 4
  • 4
  • Your first solution, does not give error code. It just gives the failed URL to me. ( Does it differ for you?) . Second approach would work but that means I will be making 2 network calls which I want to avoid. – Yahoo Mar 26 '20 at 22:48