React-Native check image url

Viewed 13854

I am trying to check if the url of an image is 404 or not. The problem is that the function is returning undefined. Why is this happening?

If I console.log the status of the res it does show 404 so the if statement is being executed.

function checkImageURL(url){
 fetch(url)
    .then(res => {
    if(res.status == 404){
      console.log(res.status)
      return <Image source={require('./Images/default.png')}/>
    }else{
      return <Image source={{uri: `${url}`}}  />
   }
 })
}
3 Answers

you are not returning anything on error response.

add .catch and return a component or null in that. for eg

function checkImageURL(URL) {
  fetch(URL)
    .then((res) => {
      if (res.status == 404) {
        return <Image source={require('./Images/default.png')} />;
      } else {
        return <Image source={{ uri: `${url}` }} />;
      }
    })
    .catch((err) => {
      return <Image source={require('./Images/default.png')} />;
    });
}

Actually, you don't need to check if the image response status it's not 404 to be able to display it. You just need to fetch your data and store it in your state, then check if the image can be displayed like the example below.

I am not exactly what are you trying to build but in my opinion, you should never make a request to fetch an image.

There is a defaultSource prop now.

<Image
  source={{ uri: 'https://example.com/image.png' }}
  style={{ height: 200, width: 200 }}
  defaultSource={defaultImg}
/>

Check the snack https://snack.expo.io/@abranhe/defaultimage

Although the selected answer solves the problem in question, the overarching problem here I notice is the way the OP is handling an image uri that returns a 404. If your intention is to have a fallback image in the case that an image's uri is invalid for whatever reason (any 400ish response), I'd recommend leveraging the onError <Image/> prop.

I have an <Avatar/> component that uses this prop:

import { Image, ImageStyle } from 'react-native'
import React, { useState } from 'react'
import { avatarPlaceholder } from '../../assets/images'

interface Props {
  avatar: string;
  style: ImageStyle;
}

const Avatar = React.memo((props: Props) => {
  const [valid, setValid] = useState(true)
  const { avatar, style } = props

  return (
    <Image
      onError={() => setValid(false)}
      style={[{
        resizeMode: "cover",
        borderRadius: 1000,
      }, style]}
      source={{ uri: valid ? avatar : avatarPlaceholder }}
    />
  )
})

export default Avatar

Happy coding!

Related