skip to Main Content

Im using this code for listing the posts


const PostList = () => {
  const [posts, setPosts] = useState({});

  const fetchPosts = async () => {
    const res = await axios.get("http://localhost:4002/posts");

    setPosts(res.data);
  };

  useEffect(() => {
    fetchPosts();
  }, []);

  const renderedPosts = Object.values(posts).map((post) => {
    return (
      <div
        className="card"
        style={{ width: "30%", marginBottom: "20px" }}
        key={post.id}
      >
        <div className="card-body" key={post.id}>
          <h3>{post.title}</h3>
          <CommentList comments={post.comments} />
          <CommentCreate postId={post.id} />
        </div>
      </div>
    );
  });

  return (
    <div className="d-flex flex-row flex-wrap justify-content-between">
      {renderedPosts}
    </div>
  );
};

export default PostList;

But im getting the error

Warning: Each child in a list should have a unique "key" prop.

Check the render method of PostList. See https://reactjs.org/link/warning-keys for more information.
at div
at PostList (http://localhost:3000/static/js/bundle.js:441:76)
at div
at App

Please help

2

Answers


  1. Render the component in this way.

    const PostList = () => {
      const [posts, setPosts] = useState({});
    
      const fetchPosts = async () => {
        const res = await axios.get("http://localhost:4002/posts");
        setPosts(res.data);
      };
    
      useEffect(() => {
        fetchPosts();
      }, []);
    
    
      return (
        <div className="d-flex flex-row flex-wrap justify-content-between">
          {posts.map((post) => (
          <div
            className="card"
            style={{ width: "30%", marginBottom: "20px" }}
            key={post.id}
          >
            <div className="card-body">
              <h3>{post.title}</h3>
              <CommentList comments={post.comments} />
              <CommentCreate postId={post.id} />
            </div>
          </div>
        ))}
        </div>
      );
    };
    
    export default PostList;
    
    Login or Signup to reply.
  2. As the warning states, each child needs to have a unique key. You assigned the same key={post.id} to both parent and child div in your renderedPosts component.

    The solution is to remove key property from the nested div:

      const renderedPosts = Object.values(posts).map((post) => {
        return (
          <div
            className="card"
            style={{ width: "30%", marginBottom: "20px" }}
            key={post.id}
          >
            <div className="card-body"> // removed key={post.id}
              <h3>{post.title}</h3>
              <CommentList comments={post.comments} />
              <CommentCreate postId={post.id} />
            </div>
          </div>
        );
      });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search