-1

i'm new to spread operations and i need some help or recommendations to add new replies to comment

my data structure is like this:

[
    {
        "id": 1,
        "content": "first comment",
        "replies": [
            {
                "id": 1,
                "comment_id": 1,
                "content": "first reply"
            },
            {
                "id": 2,
                "comment_id": 1,
                "content": "seconds reply"
            }
        ]
    },
    {
        "id": 2,
        "content": "second comment",
        "replies": [
            {
                "id": 3,
                "comment_id": 2,
                "content": "third reply"
            }
        ]
    }
]

and new data:

{
    "id": 4,
    "comment_id": 2,
    "content": "fourth reply"
}

the thing i wanted to do is:

const _reply = data =>
{
    this.setState({
        comments: // add new reply to comment by comment_id
    })
}
Kakajann
  • 124
  • 1
  • 11
  • Possible duplicate of [Whats the best way to update an object in an array in ReactJS?](https://stackoverflow.com/questions/28121272/whats-the-best-way-to-update-an-object-in-an-array-in-reactjs) – Emile Bergeron Aug 06 '19 at 15:09

3 Answers3

3
const _reply = data =>
{
    this.setState(prevState =>({
        ...prevState,
        comments : prevState.comments.map(comment => {
            if(comment.id === data.id) return {...comment, replies: comment.replies.concat(data)}

           return comment
        })
    }))
}
Dupocas
  • 20,285
  • 6
  • 38
  • 56
1
const _reply = data =>
{
    let comment = this.state.comments.find(comment => comment.id === data.comment_id)
    if (comment) {
        comment = {...comment, replies: [...comment.replies, data]};
    }
    this.setState({
        comments: [...comments]
    })
}
Morphyish
  • 3,932
  • 8
  • 26
  • This mutates the current state `comment`. – Emile Bergeron Aug 06 '19 at 15:08
  • I edited my answer to remove the mutation. I am fairly new to React, would such a mutation right before a `setState` have an impact ? – Morphyish Aug 06 '19 at 15:12
  • You should never mutate the state manually, regardless of when, since React uses it to determine if changes were made. – Emile Bergeron Aug 06 '19 at 15:14
  • 1
    I was under the impression that I should not mutate state as I had no guarantee that changes would persist, but that React was only observing changes made with `setState`. I still have much to learn ! – Morphyish Aug 06 '19 at 15:17
0

When you want to merge the data on the basis of comment_id, you can do this,

const _reply = data =>
{
  this.setState(prevState =>({
    ...prevState,
    comments : prevState.comments.map(comment => (comment.replies[0].comment_id === data.comment_id) ? {...comment, replies: comment.replies.concat(data)} : comment
        )
  }), ()=>console.log(this.state.comments))
}

Simplified Demo

ravibagul91
  • 20,072
  • 5
  • 36
  • 59