React accessing variable that's not loaded when reloading


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) => == id)[0].Notes')

This is the code that is causing the error:

        if(notes !== undefined){
            setNoteData(notes.filter(item => == id));
            setMyNotes(notes.filter(item => == id)[0].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 => == id)[0] is undefined.

try this instead:

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

Leave a Reply Cancel reply