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.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    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
    };

    chevron_right

    
    

  2. Create an object store in the database –
    // Syntax
    let objectStore = db.createObjectStore(name, [keyOption]);
    // name : object store name
    // keyOption : object property key
    
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

  3. Starting a transaction –
    // Syntax
    db.transaction(objectStore, type]);
    // objectStore : objectStore which is to be used
    // type : readonly or readwrite
    
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    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);
    };

    chevron_right

    
    

  4. Close the transaction
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    let transaction = db.transaction("books", "readwrite");
      
    // Conducting operations in the transaction
      
    // When transaction is over
    transaction.oncomplete = function() {
      console.log("Transaction is complete");
    };

    chevron_right

    
    

    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.

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.