I'm working on a plugin for Gutenberg. My plugin has to access the alt_text attribute of the post's featured image to search for a keyword in it. I access the featured image data like this:
const featuredId = select('core/editor').getEditedPostAttribute('featured_media');
const featuredMedia = featuredId ? select('core').getMedia(featuredId) : null;
console.log(featuredMedia.alt_text || 'no media');
When I load the editor, everything works as expected. But if I do any changes to the featured image (edit alt text, replace or remove the image) and run the scritpt afterwards, I get the unchanged data of the featured image. No errors or warnings. Doesn't matter if I execute the code from my js files or the browser's console. When I try editing the featured image once more I see changes in the Media Library, which is OK. The changes I made are available to JS after I save the edited post and refresh the page. How can I access the updated featured image earlier (right after I click "Set featured image" button)? Or is it a bug in WordPress/Gutenberg? Or am I missing something?
The default context for getMedia() is view which does not return a value for alt_text. To return the alt_text immediately after a featured image is set, change the context to embed:
const featuredId = select('core/editor').getEditedPostAttribute('featured_media');
const featuredMedia = featuredId ? select('core').getMedia(featuredId, { context: 'embed' }) : null;
console.log(featuredMedia.alt_text || 'no media');
The function getMedia() calls the Media REST API with any accepted parameters and returns the result. The context embed includes the alt_text in the response for images that aren't displayed.