0👍
You should specify on which comment you want to add this reply object.
Either by passing the comment id to pushReply
or by adding this id to the reply object (like parentId
).
Then, in the pushReply
function, find the comment by this id and add this reply to it.
You have several ways as this one:
const state = {
comments: [
{
id: 1,
replies: [],
parentId: null,
},
{
id: 2,
replies: [],
parentId: null,
},
{
id: 3,
replies: [],
parentId: null,
},
],
};
const reply = {
id: 1,
replies: [],
parentId: 2,
};
function pushReply(state, comment) {
if (null === comment.parentId) return; // handle this case, maybe throw an error
state.comments.find((item, i) => {
if (item.id === comment.parentId) {
state.comments[i].replies.push(comment);
}
});
}
pushReply(state, reply);
console.log(state);
Source:stackexchange.com