DEV Community

Andrés Valdivia Cuzcano
Andrés Valdivia Cuzcano

Posted on

Add data to IndexedDB

To add new objects to the Object Store, a request is made using the add(object) method of the objectStore obtained from the created transaction. Then the events are handled depending on what you want to do once the operation is completed.
The result of the request is the key of the added object.

// IndexedDB connection (IDBDatabase)
let db;

function createDatabase() {
    //...

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

    request.onsuccess = (e) => {
        // Create DB connection
        db = request.result;
    };

    //...
}


function addStudent(student){
    const transaction = db.transaction('students', 'readwrite');

    transaction.oncomplete = function(event) {
        //...
    };

    transaction.onerror = function(event) {
      //...
    };

    const objectStore = transaction.objectStore('students');

    // Add new student
    const request = objectStore.add(student);

    request.onsuccess = ()=> {
        // request.result contains key of the added object
        console.log(`New student added, email: ${request.result}`);
    }

    request.onerror = (err)=> {
        console.error(`Error to add new student: ${err}`)
    }
}

const studentA = {
        name: 'Andres',
        lastname: 'Valdivia',
        email: 'pandres@pandres.com',
        age: 22
}

addStudent(studentA)
Enter fullscreen mode Exit fullscreen mode

A short and tidy way of doing this, bearing in mind that the events of the transaction will "depend" on what happens with the request, would be:

function addStudent(student){
    const request = db.transaction('students', 'readwrite')
                                                .objectStore('students')
                                                .add(student);

    request.onsuccess = ()=> {
        console.log(`New student added, email: ${request.result}`);
    }

    request.onsuccess = (err)=> {
        console.error(`Error to add new student: ${err}`)
    }
}

const studentA = {
        name: 'Andres',
        lastname: 'Valdivia',
        email: 'pandres@pandres.com',
        age: 22
}

addStudent(studentA);
Enter fullscreen mode Exit fullscreen mode

The previous example is fine if you only want to add a student each time the function is executed. However, if you want to add several students it is best to have the transaction and the objectStore separately, since the transaction will be active as long as there are requests pending and the objectStore gives us access to the "table". Also now the events of the transaction don't "depend" on the request, for example, the complete event will be fired when ALL the objects have been added. The code would look like this:

function addStudents(students){
    const transaction = db.transaction('students', 'readwrite');

    transaction.oncomplete = function(event) {
        console.log('All the students added successfully')
    };

    transaction.onerror = function(event) {
      //...
    };

    const objectStore = transaction.objectStore('students');

    for(student of students){
        const request = objectStore.add(student);

        request.onsuccess = ()=> {
            console.log(`New student added, email: ${request.result}`);
        }

        request.onsuccess = (err)=> {
            console.error(`Error to add new student: ${err}`)
        }
    }
}

const students = [
    {name: 'name1', lastname: 'lastname1',email: 'email1@email.com', age: 22},
    {name: 'name2', lastname: 'lastname2',email: 'email2@email.com', age: 24},
    {name: 'name3', lastname: 'lastname3',email: 'email3@email.com', age: 22},
    {name: 'name4', lastname: 'lastname4',email: 'email4@email.com', age: 23},
    {name: 'name5', lastname: 'lastname5',email: 'email5@email.com', age: 22}
]

addStudents(students)
Enter fullscreen mode Exit fullscreen mode

Discussion (0)