How to get an object store from indexedDB?

I have indexedDb in my web storage application.

I would like to receive the form below in the store.

var store = myapp.indexedDB.db.transaction(['tree_nodes'],'readwrite').objectStore('tree_nodes'); 

It returns an error. I knew well about opening the indexeddb database and changing the version.

Mistake Uncaught TypeError: Cannot call method 'transaction' of null

I tried this with a breakpoint. In this case, it works fine without errors.

How can I get a store? please help me.

Thanks in advance!

+1
source share
2 answers

, , , db null. , db , db , , ​​ db, , .

( ). , promises . , . , . 'db' callback request.onsuccess . . db, ( null).

, , , , - :

// 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....
  };
}
+6

, , indexeddb .

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);
        };
};
+5

Source: https://habr.com/ru/post/1524187/


All Articles