React accessing variable that's not loaded when reloading

Advertisements

I am running into an error: I have a NotesContext that stores all the notes that the user created that are being fetched from Supabase. When I am accessing a note the page loads fine and has to issues retrieving the Note. However, when reloading I get an error that the variable cannot be undefined even though I have an if statement having don’t access it if its not loaded, this is the error:

TypeError: undefined is not an object (evaluating 'notes.filter((item) => item.id == id)[0].Notes')

This is the code that is causing the error:

    useEffect(()=>{
        if(notes !== undefined){
            setNoteData(notes.filter(item => item.id == id));
            setMyNotes(notes.filter(item => item.id == id)[0].Notes);
        }

    },[notes])

Am I doing something wrong? As this shouldn’t run its the value is undefined.

p.s – Notes is defined at the top
const {notes,setNotes} = useContext(NotesContext);

>Solution :

notes !== undefined does not check if notes.filter(item => item.id == id)[0] is undefined.

try this instead:

const note = notes.find(item => item.id == id);
if (note != null) {
    setMyNotes(note.Notes);
}

Leave a Reply Cancel reply