How to fetch featured media by post id using function

375 Views Asked by At

I am working on a Gutenberg custom block, but I'm trying to put it to fetch featured media by post id using the function. It does not work for me. What is wrong with the below code. I don't make sense. Need a little help!

const getFeaturedMediaById = (featuredMediaId) => {
        const media = useSelect(
            ( select ) =>
                featuredMediaId && select( 'core' ).getMedia( featuredMediaId ),
            [ featuredMediaId ]
        );
            return media;
};
const featured_media = getFeaturedMediaById(100);

Console error:

Uncaught Error: Minified React error #321; visit https://reactjs.org/docs/error-decoder.html?invariant=321 for the full message or use the non-minified dev environment for full errors and additional helpful warnings. 
    at Object.S (react-dom.min.js?ver=16.9.0:78)
    at useCallback (react.min.js?ver=16.9.0:31)
    at Module.Fe (data.min.js?ver=75f90354ddff4acd5b0b4026454037ca:2)
    at getFeaturedMediaById (<anonymous>:2:35)
    at <anonymous>:1:1
1

There are 1 best solutions below

0
On

Your code syntax is fine and I would suspect the issue may be that media id "100" does not exist or is restricted.

As the console error is from the minified version of the JavaScript, it's 'challenging' to debug from...

To make debugging easier, the standard workflow is to use npm start while working on your project (and debugging) and then npm run build for the final, production-ready (minified) build.

If the media id is the issue, when using npm start you would see the following error logged to the browser console:

api-fetch.min.js?ver=... GET http://example.site/wp-json/wp/v2/media/100?context=edit&_locale=user 404 (Not Found)
...
Uncaught (in promise) 
{code: "rest_post_invalid_id", message: "Invalid post ID.", data: {…}}
  code: "rest_post_invalid_id"
  data: {status: 404}
  message: "Invalid post ID."
  __proto__: Object

Alternatively, it could be you are trying to display featured_media in render() before the REST API request/promise has been fulfilled. If both the above are fine, then it would be possibly you are trying to render the object of featured_media, though you can use console.log(featured_media); to see the object that is returned.

Try using the above steps to generate an un-minified error in the console or confirm if the media id is the issue by testing with another known id. If its neither of the first two, have a look at when/how its being rendered.