Stefan
Stefan

Reputation: 3

React component not rendering despite event firing

I'm making a blog with react, next.js, and json-server. I have come as far as dynamically loading blog posts and other UI, but now when I'm trying to load the comments dynamically as well, it's not working.

The component in question is this one.

const Comments = ({ id }) => {
  const [com, setCom] = useState([]);

  useEffect(() => {
    const getComments = async () => {
      const comment = await fetchPost(id);

      if (comment["comments"].length == 0) return;

      const comments = [...comment["comments"]];

      setCom([...comment["comments"]]);
    };

    getComments();
  }, []);

  return (
    <div>
      {com.map((p) => {
        console.log(p.comment);
        <Comment key={p.id} comment={p.comment} />;
      })}
    </div>
  );
};

I know that the component is getting called and have the information as I'm logging it to console inside map. What I can't get my head around is why it is not rendering as it is a near carbon copy of how I render the blog-posts.

Aside from the above, I have tried the following:

Upvotes: 0

Views: 637

Answers (1)

Ploppy
Ploppy

Reputation: 15353

Your function is not returning anything so React has nothing to render

{com.map((p) => (
  <Comment key={p.id} comment={p.comment} />;
))}

The following code returns nothing

() => { const value = 1; }

The following code returns 1

() => { const value = 1; return value;}

The following code returns 1

() => 1

Upvotes: 2

Related Questions