Ecommerce Shopify WordPress Discussion

Gutenberg Block, getMedia() is undefined

I'm trying to get the featured image of selected post, but I'm getting undefined when I try this: const media = select('core').getMedia( FEATURED_IMAGE_ID ); console.log(media); It turns to undefined when it's first try. If trigger the function for second time, it gives the json. I tried the async function but no luck. Anyone have any ideas?
As per a similar issue in the WordPress/gutenberg repository: Since getMedia returns undefined when the data hasn't been retrieved yet, I suggest using the withSelect higher order component to do the select('core').getMedia part. Your component will re-render as soon as the data has been loaded and is available. This was posted on June 6th 2019 and thus, a more succinct solution exists as per this WordPress developer blog article: You should know that useSelect and useDispatch hooks are a more modern way of managing application state [than withSelect and withDispatch] Thus, you could use useSelect as follows in your block: function MyBlockEdit( … ) { // … const media = useSelect( select => select( 'core' ).getMedia( FEATURED_IMAGE_ID ), [ FEATURED_IMAGE_ID ], ); // … This doesn't get around the root predicament that getMedia can be undefined, but this does seem to be the recommended way to handle the result. You should perhaps consider an empty state and/or a loading state in your block.

December 29, 2023

Our products

The help you need, when you need it

App by Turbo Engine

3 apps • 5.0 average rating

Turbosify Speed Booster

5.0 (7)
Get better conversions by optimizing shopify store Google page speed Installed

Turbosify Translator for Wordpress Woocommerce

5.0 (74) Free Wordpress Woocommerce Plugin
Translate your wordpress website to multiple language within 1 click, no configuration needed, no No technical required

Grow your business here

Whether you want to sell products down the street or around the world, we have all the tools you need.