Search code examples
react-nativeimageexpoblobavatar

Image not found React Native (Expo)


Hello fellow programmers,

I am trying to show an image using the UserAvatar component in React-Native (Expo) but I am facing a problem where the link I am getting from the API is not working 404 Not Found, what is the best possible way to avoid this problem. I tried to create a blob using the URL of the image but it was not successful

This is the error message i am getting in the app

Online fetched source is not a supported image at node_modules/react-native-user-avatar/src/helpers.js:41:6 in fetchImage

Here is one of the solutions i have tried:

urlToBlob = (url) => new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onerror = reject;
xhr.onreadystatechange = () => {
  if (xhr.readyState === 4) {
    resolve(xhr.response);
  }
};
xhr.open('GET', url);
xhr.responseType = 'blob'; // convert type
xhr.send();
})this.urlToBlob(data)
        .then((blob) => {
          console.log(blob);
        });

Solution

  • The approach that i took to solve this problem is very simple.

          axios
            .get(image_url)
            .then((res) => {
              if (res.status === 200) {
                setImageStatus(200);
              }
            })
            .catch((err) => {
              setImageStatus(err.response.status);
            });
        }
    

    When the response status is 200 then the image exists if not fallback to the default image.