How to get objectstore from indexedDB?

泄露秘密 提交于 2019-12-02 05:03:05

The error is probably because your db variable is null. This is almost always because you are trying to store db in a global variable as a result of a callback, and then access the db variable in a separate function that is not guaranteed to only execute after your db variable is set, such that the browser finds you are accessing an uninitialized variable.

The solution is simple (but frustrating). You cannot use a global variable in this manner unless you want to learn about some library's implementation of promises and deferred objects. Instead, look at the answer given by Deni. Use callbacks and write your code in callback functions, not global variables. 'db' is only accessed from within the callback request.onsuccess function, and is not global. That's why Deni's will work. His code will only attempt to access db when it is guaranteed to be initialized (not null).

Since you didn't post your surrounding code, which turns out to be important, you will need to do something like this:

// I am an evil global variable that will not work as expected
myapp.indexedDB.db = 'DO NOT USE ME OR YOU WILL GET AN ERROR';

// I am a good function that only accesses an initialized db variable
function doit() {
  var request = window.indexedDB.open(......);
  request.onsuccess = function(event) {
    // Use this db variable, not your global one
    var db = event.target.result;

    // Note that you can also access the db variable using other means
    // here like this.result or request.result, but I like to use event.target
    // for clarity.

    // Now work with the db variable
    var store = db.transaction(['tree_nodes'],'readwrite').objectStore('tree_nodes');
    // do some more stuff with store....
  };
}

Here is in short what you need to do in order to get data from indexeddb First you need to open the database in order to retrieve data.

var request = indexedDB.open("tree_nodes", v); // first step is opening the database
request.onsuccess = function(e) {
        var db =  e.target.result;
        var trans = db.transaction(["tree_nodes"], 'readwrite'); //second step is opening the object store
        var store = trans.objectStore("tree_nodes");

        var request = store.get(id); //getting single object by id from object store

        request.onsuccess = function(e) {
            showDetails(e.target.result); // data retreived
            db.close();
        };

        request.onerror = function(e) {
                console.log("Error Getting: ", e);
        };
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!