Search code examples
javascriptpromiseindexeddbdexie

Dexie JS .. Delete issue


I am trying to delete a record by ID from indexedDB using dexie.js. (Dexie.js is a wrapper for indexedDB)

//Database and table structure
window.trollflixDB_offline_jokes = new Dexie("trollflixDB_offline_jokes");
trollflixDB_offline_jokes.version(1).stores({
    offline_jokes: "++id, joke_id, joke"
});

//Get data
window.get_offline_jokes = function(){
    trollflixDB_offline_jokes.offline_jokes.where('id').above(-1).limit(1).each(result => {
        console.log(result.id); //122
        del_joke(result.id);
    });
};

//Delete data
window.del_joke = function(delete_id){
    console.log(delete_id); //122
    console.log(typeof delete_id, typeof Dexie, typeof trollflixDB_offline_jokes, typeof trollflixDB_offline_jokes.offline_jokes);
    //number function object object

    trollflixDB_offline_jokes.offline_jokes.where('id').equals(delete_id).delete();
};

get_offline_jokes();

The function is working when I am trying it on DEV console or out of the function scopes. trollflixDB_offline_jokes.offline_jokes.where('id').equals(122).delete();

I tried to use different syntax, and it does not work. trollflixDB.recent_notifications.where({'id': delete_id}).delete();

Tested on Opera, Chrome. There is no any Errors, Warnings, or Promise Exceptions returned.

If you want to TEST this on your browser, here is how to put the data quickly with copy-paste to dev console...

const getScript=e=>new Promise((o,n)=>{const t=document.createElement("script");t.src=e,t.async=!0,t.onerror=n,t.onload=t.onreadystatechange=function(){const e=this.readyState;e&&"loaded"!==e&&"complete"!==e||(t.onload=t.onreadystatechange=null,o())},document.head.appendChild(t)});getScript("https://unpkg.com/dexie@2.0.4/dist/dexie.min.js").then(()=>{window.trollflixDB_offline_jokes=new Dexie("trollflixDB_offline_jokes"),trollflixDB_offline_jokes.version(1).stores({offline_jokes:"++id, joke_id, joke"}),trollflixDB_offline_jokes.offline_jokes.put({joke_id:"32HUHU)",joke:"xD XD"})});


Solution

  • Please let your promise-using functions return a promise so you can chain the calls to them.

    Regarding calling delete within Collection.each(), it is not possible because Collection.each() is readonly unless you call it from a readwrite transaction. If you want to modify things within the iteration, use Collection.modify() instead of Collection.each(). This is described in the Notes section for Collection.each: https://dexie.org/docs/Collection/Collection.each()#notes