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>
);
}
}
Simple Solution (but it's bad):
You can get the error message and check if the string includes a status code, example:
Another Solution
Using Fetch.
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?