Getting constant error of - Uncaught TypeError: Cannot read properties of undefined (reading 'map')

Viewed 459

This is one of my components in the project named Posts.jsx which displays all the posts received from a component, but as soon as I render the component the page goes blank showing :

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

Even if I write posts?. maps... it doesn't work. Please help me with this.


import Post from "../post/Post";
import "./posts.css";

export default function Posts({posts}) {
  return (
    <>
      <div className="posts">
          
          {posts.map((p) =>{
            {console.log(p)}
            <Post post = {p} />
          })}
      </div>
    </>
    
  );
}

3 Answers

Your prop posts is undefined. Check what value you pass to the component and make sure this is an array.

It happens if posts is fetched by the consumer of the component from an API trough a request for example. While the data is being fetched posts may be undefined depending on how you implement it. A solution is to check with ? (Optional Chaining Operator). Like so:

import Post from "../post/Post";
import "./posts.css";

export default function Posts({posts}) {
  return (
    <>
      <div className="posts">
          
          {posts?.map((p) =>{
            {console.log(p)}
            <Post post = {p} />
          })}
      </div>
    </>
    
  );
}

If you are still getting the error it means posts is not an array, make sure it's one when defining it, change it and also when passing it to the component.

The problem is that you imported Post with a capital P and you are trying to map post with a small p Use this code to correct it

import Post from "../post/Post";
import "./posts.css";

export default function Posts({posts}) {
  return (
    <>
      <div className="posts">
          
          {Posts.map((p) =>{
            {console.log(p)}
            <Post post = {p} />
          })}
      </div>
    </>
    
  );
}
Related