I have a button in my component that will execute DeleteNote property which i want to remove an array element on onClick event.
DeleteNote = (id) =>
{
const allNotes = [...this.state.notes];
const selectedNoteIndex = allNotes.findIndex(e => e.id == id)
allNotes.splice(selectedNoteIndex, 1)
this.setState({ notes: allNotes })
}
But this method seems to not re-render the component.
Anyway when i try with this method, it re-render perfectly.
MoveToArchive = (id) =>
{
const allNotes = [...this.state.notes];
const selectedNoteIndex = allNotes.findIndex(e => e.id == id)
allNotes[selectedNoteIndex].archived = true;
this.setState({ notes: allNotes })
}
What is lacking in my DeleteNote property in order to delete an element? Been reading all resources but nothing seems to work.
Render :
Display = () =>
{
return (
<>
<HeaderContainer notesData={this.state.notes} searchMethod={this.SearchNotes} />
<MainContainer notesData={this.state.notes} deleteMethod={this.DeleteNote} archiveMethod={this.MoveToArchive} activeMethod={this.MoveToActive} />
<NewModal />
<DeleteModal deleteAllMethod={this.DeleteAllNotes} />
</>
)
}
render()
{
return (this.Display())
}
CodePudding user response:
try this:
DeleteNote = (id) =>
{
const allNotes = [...this.state.notes];
const selectedNoteIndex = allNotes.findIndex(e => e.id == id)
allNotes.splice(selectedNoteIndex, 1)
this.setState({ notes: [...allNotes] })
}
CodePudding user response:
Can you try this code for deleting
DeleteNote = (id) => {
const newNotes = this.state.notes.filter(e => e.id !== id)
this.setState({ notes: newNotes })
}