Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If statement within return

How do I add an if statement in a return statement of this sort:

return {
    ID: select('core/editor').getEditedPostAttribute('featured_media'),
    if (ID) {
        media: select('core').getMedia( ID )
    }
};

Clearly, I can’t just drop an if statement if () directly within return {}.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There are 2 things you can do, either use a ternary operator inline:

return {
    ID: select('core/editor').getEditedPostAttribute('featured_media'),
    media: (ID ? select('core').getMedia( ID ) : undefined)
};

or create the object and conditionally add a new property

const obj = {
    ID: select('core/editor').getEditedPostAttribute('featured_media')
};

if(ID){
    obj.media = select('core').getMedia( ID )
}

return obj
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading