1

So, I'm mapping some images from the API response, and they come with an array of five img sources(urls). By default, src of the image should be first url from the given array, but in some cases that url is broken, and should be replaced with the next working url from the array. I've tried doing something like this:

<img src={snapshots[0]} alt="" onError={(e) => this.onError(e, snapshots)} />

imageExists = url => {
        let img = new Image();
        img.src = url;
        
        if (img.width !== 0) {
            return true
        } else {
            return false
        }
        
      }

onError = (e, snapshots) => {
        
       if (this.imageExists(snapshots[1])) {
            e.target.src = snapshots[1]
       } else if (this.imageExists(snapshots[2])) {
            e.target.src = snapshots[2]
        } else if (this.imageExists(snapshots[3])) {
           e.target.src = snapshots[3]
        } else if (this.imageExists(snapshots[4])) {
            e.target.src = snapshots[4]
        } else {
            e.target.src = 'https://via.placeholder.com/400x300'
       }

        
    }

But sometimes this checking method works, sometimes it doesn't, it just skips to the placeholder image, even if there are working urls. Any advice?

MikeU
  • 11
  • 2
  • If the size of image is big, it will take time to load. By that time, your check `img.width !== 0` will have been processed and would return false – Rajesh Jan 10 '19 at 08:44
  • Add `onLoad` handler to `let img` and if its called, remove handler from other images and set src of current image – Rajesh Jan 10 '19 at 08:47
  • @Rajesh I think the question seems little bit different then the one you marked as duplicate. – Just code Jan 10 '19 at 10:14
  • @Justcode Thats true. However, the real issue is in checking if the image is loaded or not. Hence, I marked it as dupe. If you strongly believe its not match, i'll reopen it and share its link – Rajesh Jan 10 '19 at 10:16
  • @Rajesh lets wait for op first – Just code Jan 10 '19 at 10:17

0 Answers0