I have a piece of state which holds an array of comments.
Each comment has an array of replies.
How can I add a reply value to the replies array of a specific comment within the comments array?
Here is my current attempt:
JavaScript
x
17
17
1
if (data) {
2
3
const isLargeNumber = (comment) => comment.id === reply.commentId;
4
5
const idx = comments.findIndex(isLargeNumber);
6
7
setPost({
8
post,
9
comments: {
10
comments[idx],
11
replies: [data.replyToComment, post.comments[idx].replies]
12
}
13
})
14
15
resetValues();
16
}
17
idx
holds the correct value I need but I do not think my implementation is correct here.
Advertisement
Answer
As post.comments
is an array, you certainly need to create an array, not a plain object with { }
. You are missing one level in your nested structure (the array of comments, versus the specific comment). You can use Object.assign
to replace the entry at [idx]
:
JavaScript
1
12
12
1
const idx = post.comments.findIndex(isLargeNumber);
2
3
setPost({
4
post,
5
comments: Object.assign([post.comments], {
6
[idx]: {
7
post.comments[idx],
8
replies: [data.replyToComment, post.comments[idx].replies]
9
}
10
})
11
});
12