reactjswordpressundefinedblockwordpress-gutenberg

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?


Solution

  • 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.