DEV Community

Andrés Valdivia Cuzcano
Andrés Valdivia Cuzcano

Posted on

5 3

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay