1

I am building a nested comment structure with React and Redux. I am having an issue with the entire tree being duplicated multiple times after I post a new reply.

I have a set of comments, that I then make into a nested format using a helper function.

I am following this answer for the recursive component: https://stackoverflow.com/a/36829986

App.js

let nestedComments = nestComments(comments);

return (
  <div>
    {nestedComments.map((comment) => (
      <Comment comment={comment} />
    ))}
  </div>
)```

In the Comment.jsx all the comments are showing in nested form using a recursive component like this:

```;
// Comment.jsx

function Comment({ comment }) {
  const nestedComments = (comment.children || []).map((comment) => {
    return <Comment comment={comment} type="child" />;
  });

  return (
    <div style={{ marginLeft: '45px', marginBottom: '10px' }} key={comment.id}>
      {console.log('Rendering a comment', comment.content)}
      <span>{comment.content}</span>
      <CommentReply parentId={comment.id} />
      {/* <a href={comment.author.url}>{comment.author.name}</a> */}
      {nestedComments}
    </div>
  );
}

So far so good, and it renders the comments in nested form like this:

enter image description here

Each of the comments have a component CommentReply to load up a comment reply box to post a new comment.

When someone adds a new comment, I will then call dispatch on redux to push the new comment to the existing comments array.

CommentReply.jsx

function handleReply(event, dispatch, parentId) {
  event.preventDefault();
  let comment = {
    id: Date.now(),
    postid: '1',
    parentId: parentId,
    userid: 'user1',
    content: event.target.content.value,
    createdAt: new Date(),
    updatedAt: new Date(),
  };

  dispatch({ type: 'SUBMIT_COMMENT', item: comment });
  console.log('Posting a reply, ', 'comment id', comment.id, 'parent id', comment.parentId);

  event.target.reset();
}

store.js

function reducer(state, action) {
  let { type, item } = action;
  let comments = [...state.comments];
  if (type === 'SUBMIT_COMMENT') {
    comments.push(item);
    console.log(comments);
    return {
      comments,
    };
  }
  return state;
}

But when I do it, it shows like this:

enter image description here

The comment tree is being duplicated a few times over and it populates.

Can you help me solve this?

The entire codebase can be found here https://github.com/TamalAnwar/nested-comments

Thank you for your time.

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
  • Maybe [this answer](https://stackoverflow.com/a/64937023/1641941) can help, it doesn't needlessly re create all comments or mutates as the other suggestions. – HMR Nov 27 '20 at 16:14

0 Answers0