Getting this error even though data confirmed to exist on the prior line! hat am I missing? TypeError: Cannot read property ‘includes’ of undefined

Here is the scenario.. I’m querying a database and populating an array full of objects. In this case the objects are articles. I am creating a filter based on categories. The goal is to run the array of objects through a filter that checks for a category match. Line 45-48 is attempting to create that filter. I declare a variable, set it equal to the result returned by the filter method. However, when the includes method executes I get an error telling me “Cannot read property includes of undefined”. Clearly as we can see in the console my array of objects is being printed from the line directly before the filter and the object clearly contains a categories field containing an array. What the hell am I not getting? Proof data is logging out from the console.log in the code

function RenderFilteredList(props) {
console.log(props.allPosts);
let filteredPosts = props.allPosts.filter((post, index) =>
  post.categories.includes(props.category)
);

return (
  <div className="posts-grid">
    {filteredPosts &&
      filteredPosts.map((post, index) => (
        <div className="grid-post-card" key={post.slug.current}>
          <Link to={"/" + post.slug.current}>
            <img
              className="grid-image"
              src={urlFor(post.featuredImage).width().url()}
              alt=""
            />
            <p className="grid-post-title">{post.title}</p>
            <p className="grid-post-author">
              {post.name + " - " + post.date}
            </p>
          </Link>
        </div>
      ))}
  </div>
);

}

Answer

In your screenshot of the console, there’s no categories shown for the fourth item in allPosts.

Since the error could occur if any item in allPosts doesn’t have categories, have you confirmed whether it’s present in all items?

You might need to change your filter function to check for the existence of the categories field and exclude items that don’t have it.