jakearchibald / idb

IndexedDB, but with promises
https://www.npmjs.com/package/idb
ISC License
6.31k stars 356 forks source link

How to use onclose event handler ? #121

Closed sidati closed 4 years ago

sidati commented 5 years ago

Hey, im wondering how to use onclose handler? Setting it directly db.onclose = () => {} fires a Uncaught (in promise) TypeError: Illegal invocation.

Any suggestions ?

sidati commented 5 years ago

Unwrapping the db object then settings up the onclose handler and re-wraping the db object again seems to solve the issue. BUT in a perfect world, passing handlers callbacks along with ["upgrade", "blocked", "blocking"] is mush better.

  let db = await openDB('dbname', 1);

  db = unwrap(db);

  Object.assign(db, {onclose: () => {
    console.log('closed');
  });

  return wrap(db);
jakearchibald commented 5 years ago

Your example above could be:

const db = await openDB('dbname', 1);
unwrap(db).onclose = () => console.log('closed');

I think I avoided the close event because of how confusing it is. It only fires if the connection is force-closed by the browser.

However, I guess I could just call it 'forceclose' instead of close.

sidati commented 5 years ago

I think forceclose is a good name for it, in my case im using it to reconnect the idb in the serviceworker since there no reload unless the serviceworker file changed, if the idb disconnected/closed somehow there no simple way to reconnected unless i used the onclose event handler.

jakearchibald commented 4 years ago

I've added this as terminated and it'll be in the next version. https://github.com/jakearchibald/idb#opendb

jakearchibald commented 4 years ago

cf041ea6e8f2e0117df51f6e91f0cff58549e8ee

sidati commented 4 years ago

Great news, thanks