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.
stateactually undefined or isreplyArrayundefined? According to your code, you're trying to grab areplyproperty of the array,commentArray. Also how are you passinghandleRemoveReplyto your component?replyArraywill always beundefinedwith the way you're initializing it since you're grabbing the property from anarrayand those don't have areplyproperty.replyArraybeingundefined?this.state.commentArray.replyis invalid. you need to pass the comment id to this handler function. thenconst idx = this.state.commentArray.findIndex( comment => comment.id === id)with that index you can properly reference the correct comment.let replyArray = this.state.commentArray[idx].reply