问题
I'm using IndexDB
to create an object store of users but when trying to add users I get an error on the var request = db.transaction(['person'], 'readwrite')
line.
The error given is:
"Uncaught TypeError: Cannot read property 'transaction' of undefined at add (test.js:32) at test.js:45"
My script looks like this:
var request = window.indexedDB.open("connectDB", 1);
request.onerror = function (event)
{
console.log('The database is opened failed');
};
var db;
request.onsuccess = function (event)
{
db = request.result;
console.log('The database is opened successfully');
};
var db;
request.onupgradeneeded = function (event)
{
db = event.target.result;
var objectStore;
if (!db.objectStoreNames.contains('users'))
{
objectStore = db.createObjectStore('users', { keyPath: 'id' });
objectStore.createIndex('name', 'name', { unique: false });
objectStore.createIndex('email', 'email', { unique: true });
}
}
function add()
{
var request = db.transaction(['person'], 'readwrite')
.objectStore('person')
.add({ id: 1, name: 'Jam', age: 24, email: 'jam@example.com' });
request.onsuccess = function (event) {
console.log('The data has been written successfully');
};
request.onerror = function (event) {
console.log('The data has been written failed');
}
}
add();
Any help would be appreciated
回答1:
It looks like you're trying to access db
during the call to add()
when it is uninitialized (note that this call to add()
occurs immediatly when your script is executed).
The db
variable is however only initialized if the database connection is successfully created:
request.onsuccess = function (event)
{
db = request.result;
console.log('The database is opened successfully');
// It is now safe to interact with the database
};
There are number of ways this problem can be addressed though the simplest would be to move your call to add()
into the onsuccess
handler like so:
request.onsuccess = function (event)
{
db = request.result;
console.log('The database is opened successfully');
add(); // Add this
};
// add(); <-- remove this from the end of your script
Finally, I noticed you have two var db;
variables declared - consider removing one of those. Hope this helps!
来源:https://stackoverflow.com/questions/53918546/cannot-read-property-transaction-of-undefined-indexeddb