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?
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.
- 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.javascript let request = indexedDB.open("gfg", 1); request.onupgradeneeded = function() { // Initialize new database }; request.onerror = function() { console.error("Unable to access database", request.error); // Logs error to the console }; request.onsuccess = function() { let db = request.result; // Use existing database };
- Create an object store in the database -
// Syntax let objectStore = db.createObjectStore(name, [keyOption]); // name : object store name // keyOption : object property key
javascript let request = indexedDB.open("gfg", 1); // Check if object store exists and // then creates it 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
javascript let transaction = db.transaction("articles", "readwrite"); // Access an object store let articles = transaction.objectStore("articles"); // Create an object let article = { id: 'Array', topic : 'Introduction to Array' }; // Add an object let request = articles.add(article); // Success request.onsuccess = function() { console.log("Article Published", request.result); }; // Failed request.onerror = function() { console.log("Article Publish failed", request.error); };
- Close the transaction
javascript let transaction = db.transaction("books", "readwrite"); // Conducting operations in the transaction // When transaction is over 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.
The usage and implementation of IndexedDB are simple. This is how you can use IndexedDB in your code through JavaScript.