Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

JavaScript Essentials - IndexedDB

Using IndexedDB for client-side storage

IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files and blobs. This tutorial covers how to use IndexedDB for persistent client-side storage in your web applications.

Key Points:

  • IndexedDB provides a way to store and retrieve large amounts of data on the client-side.
  • It supports transactions for reliability.
  • IndexedDB is asynchronous and can handle complex queries.

Opening a Database

To use IndexedDB, you first need to open a database. If the database does not exist, it will be created.


const request = indexedDB.open('myDatabase', 1);

request.onerror = function(event) {
    console.error('Database error:', event.target.error);
};

request.onsuccess = function(event) {
    const db = event.target.result;
    console.log('Database opened successfully');
};

request.onupgradeneeded = function(event) {
    const db = event.target.result;
    db.createObjectStore('myObjectStore', { keyPath: 'id' });
    console.log('Object store created');
};
                

Adding Data

To add data to an object store, you need to initiate a transaction and use the add method.


request.onsuccess = function(event) {
    const db = event.target.result;
    const transaction = db.transaction(['myObjectStore'], 'readwrite');
    const objectStore = transaction.objectStore('myObjectStore');
    const data = { id: 1, name: 'John Doe', age: 30 };
    const request = objectStore.add(data);

    request.onsuccess = function() {
        console.log('Data added to the object store');
    };

    request.onerror = function(event) {
        console.error('Add request error:', event.target.error);
    };
};
                

Reading Data

To read data from an object store, you need to initiate a transaction and use the get method.


request.onsuccess = function(event) {
    const db = event.target.result;
    const transaction = db.transaction(['myObjectStore']);
    const objectStore = transaction.objectStore('myObjectStore');
    const request = objectStore.get(1);

    request.onsuccess = function() {
        if (request.result) {
            console.log('Data retrieved:', request.result);
        } else {
            console.log('No data record found');
        }
    };

    request.onerror = function(event) {
        console.error('Get request error:', event.target.error);
    };
};
                

Updating Data

To update data in an object store, you need to initiate a transaction and use the put method.


request.onsuccess = function(event) {
    const db = event.target.result;
    const transaction = db.transaction(['myObjectStore'], 'readwrite');
    const objectStore = transaction.objectStore('myObjectStore');
    const data = { id: 1, name: 'Jane Doe', age: 32 };
    const request = objectStore.put(data);

    request.onsuccess = function() {
        console.log('Data updated in the object store');
    };

    request.onerror = function(event) {
        console.error('Update request error:', event.target.error);
    };
};
                

Deleting Data

To delete data from an object store, you need to initiate a transaction and use the delete method.


request.onsuccess = function(event) {
    const db = event.target.result;
    const transaction = db.transaction(['myObjectStore'], 'readwrite');
    const objectStore = transaction.objectStore('myObjectStore');
    const request = objectStore.delete(1);

    request.onsuccess = function() {
        console.log('Data deleted from the object store');
    };

    request.onerror = function(event) {
        console.error('Delete request error:', event.target.error);
    };
};
                

Handling Errors

Proper error handling is essential when working with IndexedDB. Always use onerror handlers to manage errors gracefully.


request.onerror = function(event) {
    console.error('Database error:', event.target.error);
};

request.onsuccess = function(event) {
    const db = event.target.result;
    console.log('Database opened successfully');
};

request.onupgradeneeded = function(event) {
    const db = event.target.result;
    db.createObjectStore('myObjectStore', { keyPath: 'id' });
    console.log('Object store created');
};
                

Summary

In this tutorial, you learned how to use IndexedDB for client-side storage in JavaScript. IndexedDB allows you to store significant amounts of structured data, providing powerful capabilities for offline and web applications.