DEV Community

Andrés Valdivia Cuzcano
Andrés Valdivia Cuzcano

Posted on

Delete data from IndexedDB

The steps to remove objects from an Object Store are similar to when they are added. First, a request to delete an object is created using the delete(key) method, and finally the events are handled as required.

function removeStudent(key){
    const request = db.transaction('students', 'readwrite')
                      .objectStore('students');
                      .delete(key);

    request.onsuccess = ()=> {
        console.log(`Student deleted, email: ${request.result}`);
    }

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

removeStudent('andres@andres.com');
Enter fullscreen mode Exit fullscreen mode

Clear

You can also remove all data stored in an Object Store with the clear() method.

function emptyStore(storeName){
    const request = db.transaction(storeName, 'readwrite')
                      .objectStore(storeName);
                      .clear();

    request.onsuccess = ()=> {
        console.log(`Object Store "${storeName}" emptied`);
    }

    request.onerror = (err)=> {
        console.error(`Error to empty Object Store: ${storeName}`)
    }
}

emptyStore('students');

Enter fullscreen mode Exit fullscreen mode

Discussion (0)