Trouble displaying featured media on list component

Hello!

I am trying to add in my post’s featured image to the List component covered in the Frontity tutorial. Currently, I have the below as my code:

import React from "react"
import { connect } from "frontity"
import Link from "@frontity/components/link"
import { Items, Card, PrevNextNav } from './styles'

const List = ({ state, actions, libraries }) => {
  const data = state.source.get(state.router.link)
  const Html2React = libraries.html2react.Component;

  return (
    <>
      <h1>Projects</h1>
      <Items>
        {data.items.map((item) => {
          const post = state.source[item.type][item.id]
          const featuredMedia = state.source.attachment[item.featured_media];
          return (

            <Link key={item.id} link={post.link}>
              <Card>
                <img src={featuredMedia.source_url} />
                <p><Html2React html={post.title.rendered} /></p>
                {post.categories.map(category => {
                  const cat = state.source.category[category]
                  return (
                    <p key={item.id + "-category"}>{cat.name}</p>
                  )
                })}
              </Card>
            </Link>
          )
        })}
        <PrevNextNav>
          {data.previous && (
            <button
              onClick={() => {
                actions.router.set(data.previous)
              }}
            >
              &#171; Prev
            </button>
          )}
          {data.next && (
            <button
              onClick={() => {
                actions.router.set(data.next)
              }}
            >
              Next &#187;
            </button>
          )}
        </PrevNextNav>
      </Items>
    </>
  )
}

export default connect(List)

However, when I use this code, I get the following error:

TypeError: undefined is not an object (evaluating 'featuredMedia.source_url')

I was wondering if anyone had any feedback or suggestions to try to solve this error?

Thanks so much in advance!

After some digging I found one of my posts did not have a featured image and this was causing the error for the map function.

1 Like