Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

This is the code that is causing the error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading