0

I have a react app which displays posts by using the WP Rest APi.

To display, I'm using map() to loop through the posts.

        {posts.map((articles, i) => {
            return (
                <Post
                key={posts[i].id}
                id={posts[i].id}
                title = {posts[i].title.rendered}
                link = {posts[i].link}         
                img = {posts[i]._embedded['wp:featuredmedia'][0].source_url}
                category = {posts[i].categories}
                />
            )
        })
    }

Because the first post doesn't have a featured image, the component breaks and I get the following console error message

Uncaught TypeError: Cannot read properties of undefined (reading '0')

If I remove the img prop, there are no issues, everything displays correctly.

Do I need to wrap the img prop into a conditional? Can you please advise on how I can fix the issue?

Any help much appreciated.

2
  • This is really just a JavaScript question. Yes you need to check for the existence of object properties before accessing them. This is easier if you use optional chaining: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Oct 26, 2022 at 5:03
  • Thanks Jacob. I've added the ? but still not working. img = {post?._embedded['wp:featuredmedia'][0].source_url}
    – rikardo85
    Commented Oct 27, 2022 at 8:30

1 Answer 1

1

Resolved!

If no feature image exists, then _embedded['wp:featuredmedia'] is not used.

To resolve, the prop value needs to be wrapped into a conditional.

<Post
key={post?.id}
id={post?.id}
title = {post?.title.rendered}
link = {post?.link}
img = {post && post._embedded && post._embedded['wp:featuredmedia'] ? post._embedded['wp:featuredmedia'][0].source_url : ' ' }
category = {post?.categories}
/>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.