GuillaumeC GuillaumeC - 1 year ago 71
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: [ => === ? { id:, comments: [...i.comments, commentToAdd.comment] } : i) ] });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download