0

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.

GuillaumeC
  • 535
  • 1
  • 8
  • 18
  • https://stackoverflow.com/questions/29537299/react-how-do-i-update-state-item1-on-setstate-with-jsfiddle – paqash Feb 26 '17 at 23:26
  • Possible duplicate of [React: How do I update state.item\[1\] on setState? (with JSFiddle)](http://stackoverflow.com/questions/29537299/react-how-do-i-update-state-item1-on-setstate-with-jsfiddle) – paqash Feb 26 '17 at 23:27

2 Answers2

1

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) ] });
m1kael
  • 2,801
  • 1
  • 15
  • 14
  • Thanks m1kael, is it the best practice or is there a better way ? – GuillaumeC Feb 27 '17 at 23:27
  • You're welcome @GuillaumeC. This is the most concise option I can think of. It doesn't mutate the original `messages` array. I'd call it a best practice approach. – m1kael Feb 28 '17 at 00:27
1

The best practice is to keep state in the normalized shape, so instead of arrays, you would have objects indexed by id, and instead of storing comments inside messages you would store only ids. For your example the state would look like this:

{
  messages: {
    byId: {
      '1': { id: '1', comments: ['comment1'] },
      ...
    },
    allIds: ['1', ...]
  },
  comments: {
    byId: {
      'comment1': { id: 'comment1', ... },
      ...
    },
    allIds: ['comment1', ...]
  }
}

In such structure in order to add a new comment you will have to update comments part and add a new id in messages[id].comments... but it's now much easier to update single comment.

For normalizing objects to such form I recommend normalizr.

More information about normalizing state shape in redux documentation Normalizing State Shape

Michał
  • 895
  • 6
  • 15