I have a button that deletes a note, and it is supposed to automatically select the next note after the first note is deleted. However, it is not working, and i have this error
Uncaught TypeError: Cannot set properties of undefined (setting 'selected')
import React, { useContext } from 'react';
import trashicon from '../../trashicon.png'
import {NoteContext} from '../../noteContext';
const DeleteNote = () => {
const [notes, setNotes] = useContext(NoteContext);
const handleDeleteNote =()=> {
const newNotesList = notes.filter(itemChecked=>itemChecked.selected===false)
console.log(newNotesList[0])
for (let i = 0; i < notes.length; i++) {
if(notes[i].selected === true) {
newNotesList[i].selected = true;
}
}
console.log(newNotesList);
setNotes(newNotesList);
}
return (
<img src={trashicon} className="delete-icon" onClick={handleDeleteNote}/>
)
}
export default DeleteNote
This logic is quite incorrect, what if notes arr has 5 objects, and newNotesList returns 3 different objects, then when you loop it will update first 3 incorrect objects in the newNotesList array.
IMO, this should be the correct logic.
if (!newNotesList.length) return;
for (let i = 0; i < notes.length; i++) {
//
}
if(notes[i].selected === true) {
const findElementInNewNotesList = newNotesList.find(el => el.id === notes[i].id);
if(findElementInNewNotesList.id) newNotesList[i].selected = true;
}
This way you're finding the matching object ONLY from newNotesList.