I'm creating simple comment box where user can reply on comment . I have defined state as follows :
this.state = {
comments: [
{
id: "TKT4321",
message: "abc",
},
{
id: "TKT34341",
message: "cccccc",
reply: [
{ id: "TKT34343", message: "aaaaa" },
]
},
],
}
one object of coments is one comment and reply is user replied on that comment
{
id: "TKT34341",
message: "cccccc",
reply: [
{ id: "TKT34343", message: "aaaaa" },
]
},
what i want to do is when user replied on comment let's say on comment having id "TKT4321" then add reply object to that list . e.g
{
id: "TKT4321",
message: "abc",
reply: [
{ id: "TKT34343", message: "gfgfg" },
]
},
If the replies are already there in the reply array then just append { id: "TKT341113", message: "ftrdgf" } object to reply array. e.g
{
id: "TKT34341",
message: "cccccc",
reply: [
{ id: "TKT34343", message: "aaaaa" },
{ id: "TKT341113", message: "ftrdgf" },
]
},
my soltuion is :
this.setState((state) => {
const { comments } = state.comments
return comments.map((item) => ({
...item,
reply: [...item.reply, { id: "TK2222", message: "jkjk" }]
}))
})
But with this i'm not able to set the state. I'm new to react and i'm confused how to set the state of nested objects. Please help.