DEV Community

Andrés Valdivia Cuzcano
Andrés Valdivia Cuzcano

Posted on

Eliminando datos de la BD

La forma de remover objetos de un Object Store es similar a cuando se agregan. Primero, se crea un request para eliminar un objeto mediante el método delete(key) y, finalmente, se manejan los eventos como sea necesario.

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

Tambien se puede eliminar todos los datos almacenados en un Object Store con el método clear().

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

Top comments (0)