Using IndexedDB when my app first runs I populate it with some data, I want to ensure that when the database and tables are created that they do not already exists.
Can I query the length of a table to see if it contains and data in JavaScript?
Using IndexedDB when my app first runs I populate it with some data, I want to ensure that when the database and tables are created that they do not already exists.
Can I query the length of a table to see if it contains and data in JavaScript?
We can use the objectStoreNames property of IndexDB to check the existence of an ObjectStore.
var db_object, object_store;
if( !db.objectStoreNames.contains(currentobjectstore) )
{
db_object = i_db.createObjectStore(currentobjectstore, {autoIncrement:true} );
object_store = db.transaction(currentobjectstore, 'readwrite').objectStore(currentobjectstore);
} else {
object_store = db.transaction(currentobjectstore, 'readwrite').objectStore(currentobjectstore);
}
Best way is trying to open objectStore in try catch block. It is synchronous also. In case of an error you can create store for example:
var store;
try {
store = request.transaction.objectStore('yourStore');
}
catch(e) {
store = db.createObjectStore('yourStore');
}
You can use objectStore.count() function, but i recommend storing some kind of meta-data that would say that your local db is initialized. Otherwise, you can have page-reload in middle of data creation and never have your data fully synced with remote data.
The database is created if a database with the specified name does not exist else it opens it
eg.var request = indexedDB.open("DataTbl");
So if your db already exists it will just open it and about you checking if the contents in the table already exists then you can make an xyz objectstore and store some key/value flag pair inside it saying that the insertion was successful and check it later everytime when page is reloaded.
Also you can give at try to count function specified by @toske
ref :
© 2022 - 2024 — McMap. All rights reserved.