Home > Blockchain >  I am trying to delete a note in react but I am getting an error that you cannot access new notes bef
I am trying to delete a note in react but I am getting an error that you cannot access new notes bef

Time:08-30

React Find error in delete note function that can't acces the newNotes befor initialization thats why that note can not be deleted?

The deleteNote function is working because its console log the message with the id that i written in it but it does'not delete the note,I already declare the newNote and initial the value in it but i can't understand why it gave the error?

    const [notes, setNotes] = useState(notesInitial) 
    //Add Note
    const addNote = (title, description, tag) => {
        //TODO API CALL
        console.log("adding a new note");
        const note = {
            "_id": "63074e71318fac99be7ce65a",
            "user": "62ee8f0b86e5c4946d3b75d5",
            "title": title,
            "description": description,
            "tag": tag,
            "date": "2022-08-25T10:26:57.324Z",
            "__v": 0
        };
        setNotes(notes.concat(note));
    }



    //Delete A Note
    const deleteNote = (id) => {

        console.log("The node delteing with id"   id);
        I think I missing something here
        const newNotes = newNotes.filter((notes) => { return notes._id !== id })
        setNotes(newNotes);
    }




    return (
        <noteContext.Provider value={{ notes, addNote, deleteNote, editNote }}>
            {props.children}
        </noteContext.Provider>
    )

}


export default NoteState;

CodePudding user response:

yes you made mistake here so convert it from

 //Delete A Note
    const deleteNote = (id) => {

        console.log("The node delteing with id"   id);
        I think I missing something here
        const newNotes = newNotes.filter((notes) => { return notes._id !== id })
        setNotes(newNotes);
    }

to

const deleteNote = (id) => {

        console.log("The node delteing with id"   id);
        I think I missing something here
        const newNotes = notes.filter((note) => { return note._id !== id })
        setNotes(newNotes);
    }

CodePudding user response:

const newNotes = newNotes.filter((notes) => { return notes._id !== id })

newNotes are being declared again and it won't take from your useState one. In the deleteNode function name it anything else.

const deleteNote = (id) => {

        console.log("The node delteing with id"   id);
        I think I missing something here
        const newNotes2 = notes.filter((notes) => { return notes._id !== id })
        setNotes(newNotes2);
    }
  • Related