score:1

Accepted answer

to trigger image onload listener it should be mounted to the dom, otherwise your setimagesize not called. to do this you should have valid images and attach it somewhere to the html, like this:

  const urls = {
    small: 'https://dummyimage.com/600x400/000/fff',
    medium: 'https://dummyimage.com/600x400/000/fff',
    large: 'https://dummyimage.com/600x400/000/fff',
  }
  
  const getimagesize = () => {
    for (const url in urls) {
      const img = new image()
      img.src = urls[url]
      img.onload = () => {
        setimagesize(prev => {
          return {
            ...prev,
            [url]: {
              width: img.width,
              height: img.height,
            },
          }
        })
      }
      document.body.appendchild(img)
    }
  }

  useeffect(() => {
    getimagesize()
  }, [])

score:0

try this below code:

const [imagesize, setimagesize] = usestate({});

const urls = {
  small: https://image1.com,
  medium: https://image2.com,
  large: https://image3.com,
}; 

const getimagesize = () => {
 for (const size in urls) {
    var img = new image();
    img.onload = function() {
      setimagesize((prev) => {
       return {
        ...prev,
        [size]: {width: this.width, height: this.height}
      }
     })
    };
   img.src = url;
  }
}

useeffect(() => {
 getimagesize()
}, [])

score:0

check the fiddle link i hope it will work[https://jsfiddle.net/k7bue0ho/][1]


Related Query

More Query from same tag