Search code examples
javascriptreactjsecmascript-6es6-promise

JS / React - Function returns undefined before finished


In my React application I have created a function to get a particular image size from an array which contains data about the image such as mimetype, available sizes, paths, etc.

export default function getImageSize(image, size) {

    // Map through each available size for the image
    image.sizes.forEach((v, i) => {

        // Return the fullpath if there is a match for the requested size
        if (v.type === size) {
           return v.fullpath;
        }

    });

}

I am calling this function with:

let smallImageSize = getImageSize(data.images[0], 'small');

And using it in my page with:

<img alt="thumbnail" src={smallImageSize} />

As you can probably guess (for the more experienced), my function returns undefined as the loop inside the function has not returned before the function is finished.

My question is, how can I ensure that my function will WAIT for a return value before anything else within my render function continues? Is using a promise the only way?

Thanks for your help.


Solution

  • The issue lies in your forEach loop. Returning a value from a forEach loop does not actually do anything.

    You need to use find instead:

    export default function getImageSize(image, size) {
    
        // Map through each available size for the image
        const img = image.sizes.find(v => {
    
            // Return the image if there is a match for the requested size
            if (v.type === size) {
               return true;
            }
    
        });
    
        // img can be undefined if it does not exist
        return img && img.fullpath;
    }