Skip to content
Advertisement

Adding value to an array in useState but only at a particular index of the array

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

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
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement