Reputation: 1
I'm having problems trying to delete one reply in my comment app project. The onClick function for the delete button for my reply keeps deleting the entire comment instead of just 'one' replies iterations that is in the reply array in state. It has to deal with how I'm referencing the state of the array of replies that I have. I'm not sure how to reference the state of the array due to my state.
I've already tried to reference state as a variable that will then reference the array in state.
//State for component
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
commentArray: [
{
message: "Hello",
showReply: false,
reply: [
{ replies: "Hi there." },
],
id: 1
}]
}
//Function to splice one reply
handleRemoveReply = (index) => {
let replyArray = this.state.commentArray.reply
this.setState({
reply: replyArray.splice(index, 1)
})
}
}
I'm expecting only one reply to delete, not the entire comment. With the things that I tried, I'm only able to delete the entire comment it seems. It keeps saying that the state is undefined, so it is a reference problem.
Upvotes: 0
Views: 238
Reputation: 1169
As far as I can tell your not actually interacting with the state correctly for your state data structure. You must first get the replyArray for the given comment, and then you need to set the state back to the origonal data structure. Also to note is that splice performs the splice operation on the array however returns the object removed. Hence unless you want to set the state to what was removed you want to first splice the array and then set the state to the new result.
//Function to splice one reply
handleRemoveReply = (index) => {
let replyArray = this.state.commentArray.reply
this.setState({
reply: replyArray.splice(index, 1)
})
}
}
Try this:
// Also pass what comment index you are interacting with
handleRemoveReply = (commentIndex, index) => {
const commentArray = [...this.state.commentArray]
commentArray[commentIndex].reply.splice(index, 1)
this.setState({
commentArray
})
}
}
Edit: updated to copy state instead of directly mutate it
Upvotes: 1