I have indexedDb on my app for web storage.
I would like to get the store form the below code.
var store = myapp.indexedDB.db.transaction(['tree_nodes'],'readwrite').objectStore('tree_nodes');
It returns error. I was well known of opening indexeddb database and version changing.
The error is Uncaught TypeError: Cannot call method 'transaction' of null
I was tried it with the break point. In that case it works fine without errors.
How can i get the store? please help me.
Thanks in advance!
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....
};
}