Search code examples
javascriptindexeddbdexie

Event fired when IndexedDb altered?


We're using DexieJS as a wrapper around IndexedDb and are looking for a way to determine if the underlying DB schema changes. Worst case, this is a user deleting a table, or the entire DB, in the midst of using our application (unlikely? sure, but come on - users).
Alternately, does IndexedDb record anything like a "Last Modified" value? We could make that work if that was all we had available. Subscribable events would be better, though... Does IndexedDb or Dexie support anything like this?


Solution

  • Schema changes have to go through a version upgrade in IndexedDB and there's an event "onversionchange" that is triggered whenever schema is altered. Dexie describe the event here: https://dexie.org/docs/Dexie/Dexie.on.versionchange.

    If you want to be notified for normal non-schema changes like table.clear(), you should try the latest alpha version of dexie (3.1.0-alpha.8) that supports cross-window/worker table observation. See release notes for 3.1.0-alpha.1 or this blog post. In your case, you'd probably want to observe any change on entire table. To do that, use:

    const observable = liveQuery(() => db.yourTable.toArray());
    

    There's also a lower level event in case you prefer to just be notified without requerying the data: See this issue comment.

    Note that dexie can only observe changes that origins from code that use dexie to mutate data. It does not react to changes that goes directly to indexedDB API because there is no such native event in the DOM API.