jakearchibald / idb

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

Support request: how to seed/populate the database during update? #254

Closed alexiusp closed 2 years ago

alexiusp commented 2 years ago

I'm trying to populate my database with some initial records. I'm trying to do that inside the update function. This is how I try to do it:

const store = db.createObjectStore(DBStoreName, { keyPath: 'id', autoIncrement: true });
store.createIndex('name', 'name');
store.transaction.oncomplete = () => {
  const objectStore = db.transaction(DBStoreName, 'readwrite').objectStore(DBStoreName);
  data.forEach((item) => objectStore.add(item));
};

This approach fails with an error: Uncaught (in promise) DOMException: Failed to execute 'transaction' on 'IDBDatabase': One of the specified object stores was not found.

Can you recommend a proper way to populate the database? Would be great to have an example somewhere in the readme.

alexiusp commented 2 years ago

Seems like the error was happening because of another reason. the code shown in my comment seems to work properly and seed the database after i fixed another issue. But still I think it has sense to mention the seeding process in the readme.

jakearchibald commented 2 years ago

I think your example is overcomplicating things.

It could just be:

const db = await openDB('db-name', 1, {
  upgrade(db) {
    const store = db.createObjectStore('store-name', {
      keyPath: 'id',
      autoIncrement: true,
    });
    store.createIndex('name', 'name');
    for (const item of data) store.add(item);
  },
});
alexiusp commented 2 years ago

Thank you, I will try this.

I found this example somewhere in the IndexedDB documentation or on StackOverflow. Would be great if this topic could be covered in the readme as well.

jakearchibald commented 2 years ago

I'm not sure the readme is the right place. Eg, why document this but not the rest of IndexedDB? At some point I'll write a larger guide to using IndexedDB with this library.