How to get React Native image failure error code

2k Views Asked by At

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>
    );
  }
}

1

There are 1 best solutions below

1
On

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?