GuillaumeC GuillaumeC - 9 months ago 38
React JSX Question

Update a nested value in a store

I have my state with the following structure:

{ messages:
[
{ id: 1, comments: []}
]
}


And I would like to add a new comment in my message, I have the message id so I can easily create a new state, loop over the messages, and add the new comment, but it doesn't seem to be the right way...

Thank you for your help.

Answer Source

Try this:

var commentToAdd = { id: 1, comment: "text" };
this.setState({ messages: [...this.state.messages.map(i => i.id === commentToAdd.id ? { id: i.id, comments: [...i.comments, commentToAdd.comment] } : i) ] });