Search code examples
reactjswordpresswordpress-rest-apiwordpress-gutenberggutenberg-blocks

WP API in React Js (Gutenberg Editor) : Cannot read property 'wp:featuredmedia' of undefined even with condition


I've built a dynamic block in Gutenberg editor for latest custom posts.

And fetched featuredmedia for them through _embed. So it's working if all my posts have featured image, but if not I have an error in console:

TypeError: Cannot read property 'wp:featuredmedia' of undefined

So I made condition, but having the same error. What am I doing wrong? Here is my code:

import { Component } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { withSelect } from '@wordpress/data';

class PortfolioPostsEdit extends Component {
    render() {
        const { posts, className } = this.props;
        return (
            <>
                {(posts && posts.length > 0) ?
                    <div className={className}>
                        {posts.map(post => (
                            <article key={post.id}>
                                <a href={post.link}>
                                    {post.title.rendered}
                                </a>
                                {post._embedded['wp:featuredmedia'] &&
                                    <div className="image">
                                        <img src={post._embedded['wp:featuredmedia'[0].source_url} />  
                                    </div>
                                }
                            </article>
                        ))}
                    </div>
                : <div>{__("No Posts Found", "my-blocks")}</div>
                }
            </>
        )
    }
}

export default withSelect(
    (select, props) => {
        return {
            posts: select('core').getEntityRecords('postType', 'my_portfolio', 'per_page: 20', '_embed: true')
        }
    }
)(PortfolioPostsEdit);

I can't understand why my condition doesn't work:

{post._embedded['wp:featuredmedia'] &&
    <div className="image">
        <img src={post._embedded['wp:featuredmedia'[0].source_url} />  
    </div>
}

Can someone help me, please? Thanks.


Solution

  • This mean post._embedded is undefined. Try this:

    post && post._embedded && post._embedded['wp:featuredmedia'] // make sure post._embedded is defined