Sunday, October 6, 2024
Google search engine
HomeLanguagesJavascriptIndexedDB | Introduction

IndexedDB | Introduction

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.

IndexedDB

Inside a database

Why use IndexedDB?

  1. 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.
  2. It is similar to a JavaScript Object, it can also have nested objects and properties.
  3. 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.

  1. 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() {
      // 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
    };

    
    
  2. 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);
      
    // 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'});  
      }
    };

    
    
  3. 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");
      
    // 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);
    };

    
    
  4. Close the transaction




    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.

Use of IndexedDB

The usage and implementation of IndexedDB are simple. This is how you can use IndexedDB in your code through JavaScript.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments