Search code examples
javascriptindexeddbonload

window.onload starts before indexed db statements


Good afternoon all,

My issue is javascript related, I have made one function called checkflights, a series of statements to open an indexeddb database and one window.onload that triggers checkflights.

It seems that the window.onload triggers before the open database statements and therefor the checkflights function does not run properly as the db is considered null.

Any solution? code here below. Thank you in advance for your support.

    var db = null
    const request = indexedDB.open('MyDataBase', '1')

    //on upgrade needed
    request.onupgradeneeded = e => {
        var db = e.target.result
        /* note = {
            title: "note1",
            text: "this is a note"
        }*/
        const myFlights = db.createObjectStore("my_flight", {
            keyPath: "flightid"
        })
        
    }
    
    request.onsuccess = e => {
        var db = e.target.result 
    
    }

    request.onerror = e => {
        alert(`error: ${e.target.error} was found `)
    }    

window.onload = function () {
        checkFlights()

    }

function checkFlights() {
        const tx = db.transaction("my_flight", "readonly");
        // var objectStore = transaction.objectStore('my_flight');
        const mesVols=tx.objectStore("my_flight")

        var countRequest = mesVols.count();
        countRequest.onsuccess = function() {
            console.log(countRequest.result);
            if(countRequest.result>0 && window.navigator.onLine){
                sendFlights()
                notify("Flights sent to server")
                }
        }
    }

Solution

  • You are redeclaring db from the outer scope, by using var again. When using var in a local scope, you are not affecting the variable from the outer scope and actually creating a new local db variable.

     var db = null
        const request = indexedDB.open('MyDataBase', '1');
        //on upgrade needed
        request.onupgradeneeded = e => {
             db = e.target.result
            /* note = {
                title: "note1",
                text: "this is a note"
            }*/
            const myFlights = db.createObjectStore("my_flight", {
                keyPath: "flightid"
            })
            
        }
        
        request.onsuccess = e => {
             db = e.target.result 
        
        }
    
        request.onerror = e => {
            alert(`error: ${e.target.error} was found `)
        }    
    
    window.onload = function () {
            checkFlights()
    
        }
    
    function checkFlights() {
            const tx = db.transaction("my_flight", "readonly");
            // var objectStore = transaction.objectStore('my_flight');
            const mesVols=tx.objectStore("my_flight")
    
            var countRequest = mesVols.count();
            countRequest.onsuccess = function() {
                console.log(countRequest.result);
                if(countRequest.result>0 && window.navigator.onLine){
                    sendFlights()
                    notify("Flights sent to server")
                    }
            }
        }
    

    As suggested by @Kinglish in a comment above, you might need to wait for the request to be handled. IndexedDB does not return a promise but you could write an async/await wrapper yourself around the top part or consider using a library like https://github.com/jakearchibald/idb that will Promisify indexedDB.