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:
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:
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.