IndexedDB is a key-value database in the browser. It is a NoSQL Database. It is transactional, i.e. if a particular action falls within a transaction, none of the actions of that transaction is applied. This ensures the database remains consistent.
Why use IndexedDB?
- The localStorage was designed for smaller amounts of data and can only store string data for keys and values whereas IndexedDB can work with a large amount of unstructured data, including Files/Blobs.
- It is similar to a JavaScript Object, it can also have nested objects and properties.
- It can be accessed asynchronously, it can be used with service workers which helps to store the data offline and once the device gains Internet access it synchronizes it to the servers.
Using IndexedDB: JavaScript is used to access IndexedDB.
- Open a Database –
// Syntax
let request = indexedDB.open(name, version);
// name : database name, string value
// version : version number, by default 1, positive integer
The code to open a database should check if the database exists or not.
let request = indexedDB.open( "gfg" , 1);
request.onupgradeneeded = function () {
};
request.onerror = function () {
console.error( "Unable to access database" , request.error);
};
request.onsuccess = function () {
let db = request.result;
};
|
- Create an object store in the database –
// Syntax
let objectStore = db.createObjectStore(name, [keyOption]);
// name : object store name
// keyOption : object property key
let request = indexedDB.open( "gfg" , 1);
request.onupgradeneeded = function () {
let db = request.result;
if (!db.objectStoreNames.contains( 'articles' )) {
db.createObjectStore( 'articles' , {keyPath: 'id' });
}
};
|
- Starting a transaction –
// Syntax
db.transaction(objectStore, type]);
// objectStore : objectStore which is to be used
// type : readonly or readwrite
let transaction = db.transaction( "articles" , "readwrite" );
let articles = transaction.objectStore( "articles" );
let article = {
id: 'Array' ,
topic : 'Introduction to Array'
};
let request = articles.add(article);
request.onsuccess = function () {
console.log( "Article Published" , request.result);
};
request.onerror = function () {
console.log( "Article Publish failed" , request.error);
};
|
- Close the transaction
let transaction = db.transaction( "books" , "readwrite" );
transaction.oncomplete = function () {
console.log( "Transaction is complete" );
};
|
We can forcefully abort the transaction by transaction.abort() method.
The usage and implementation of IndexedDB are simple. This is how you can use IndexedDB in your code through JavaScript.
Last Updated :
22 Jun, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...