0

My problem is simple, but incredibly frustrating as I'm now on my second week of trying to figure this out and on the verge of giving up. I would like to retrieve my 'notesObject' variable outside my getAllNotes() function when after the transaction.oncomplete() listener executes.

 (function() {
        // check for IndexedDB support
        if (!window.indexedDB) {
            console.log(`Your browser doesn't support IndexedDB`);
            return;
        }

        // open the CRM database with the version 1
        let request = indexedDB.open('Notes', 1);

        // create the Contacts object store and indexes
        request.onupgradeneeded = (event) => {
            let db = event.target.result;

            // create the Notes object store ('table') 
            let store = db.createObjectStore('Notes', {
                autoIncrement: true
            });

            // create an index on the sections property.
            let index = store.createIndex('Sections', 'sections', {
                unique: true
            });

        }

        function insertData() {
            let myDB = indexedDB.open('Notes');

            myDB.onsuccess = (event) => {
                // myDB.transaction('Notes', 'readwrite')
                event.target.result.transaction('Notes', 'readwrite')
                    .objectStore('Notes')
                    .put({
                        sections: "New Note",
                        pages: "New page",
                        lastSelectedPage: ""
                    });

                console.log("insert successful");
            }

            myDB.onerror = (event) => {
                console.log('Error in NotesDB - insertData(): ' + event.target.errorCode);
            }

            myDB.oncomplete = (event) => {
                myDB.close();
                console.log('closed');
            }
        }

        insertData()

        function getAllNotes() {
            let myDB = indexedDB.open('Notes');
            let notesObject = [];

            myDB.onsuccess = (event) => {
                let dbObjectStore = event.target.result
                    .transaction("Notes", "readwrite").objectStore("Notes");

                dbObjectStore.openCursor().onsuccess = (e) => {
                    let cursor = e.target.result;

                    if (cursor) {
                        let primaryKey = cursor.key;
                        let section = cursor.value.sections;

                        notesObject.push({
                            primaryKey,
                            section
                        })
                        cursor.continue();
                    }
                }

                dbObjectStore.transaction.onerror = (event) => {
                    console.log('Error in NotesDB - getAllData() tranaction: ' + event.target.errorCode);
                }

                dbObjectStore.transaction.oncomplete = (event) => {
                    return notesObject; 
                    console.log(notesObject) 
                }
            }

        }

        let notes = getAllNotes()
        console.log("Getting Notes sucessful: " + notes)

    })()

I've tried setting global variables, but nothing seems to work. I am a complete noob and honestly, I'm completely lost on how to retrieve the notesObject variable outside my getAllNotes() function. The results I get are 'undefined'. Any help would be greatly appreciated.

  • Take the time to learn about `Promise`s. This is a hard concept to learn but once you sort of get it, the answer to your question will be very clear. Every developer has to go through this crucible of learning about it, and it is not something that can be briefly explained to you. – Josh Nov 11 '22 at 20:02

1 Answers1

1

This is effectively a duplicate of Indexeddb: return value after openrequest.onsuccess

The operations getAllNotes() kicks off are asynchronous (they will run in the background and take time to complete), whereas your final console.log() call is run synchronously, immediately after getAllNotes(). The operations haven't completed at the time that is run, so there's nothing to log.

If you search SO for "indexeddb asynchronous" you'll find plenty of questions and answers about this topic.

Joshua Bell
  • 7,727
  • 27
  • 30