jakearchibald / idb

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

Get generated key from autoIncrement field #96

Closed 8alery closed 5 years ago

8alery commented 5 years ago

Good afternoon! I tried to get the value of autoIncrement field but add method on db object returns undefined. But new item is added, I can see it after I refresh page. I couldn't find information on it in docs so I'd like to ask how can I get this generated id? My code is like this:

import { openDB } from 'idb';
const dbPromise = openDB('investment_db', 1, {
    upgrade(db) {
        const ordersStore = db.createObjectStore('orders', {
            keyPath: 'id',
            autoIncrement: true,
        });
        ordersStore.createIndex('purchaseDate', 'purchaseDate');
    },
});
export default {
        async addOrder(order){
        return (await dbPromise).add('orders', order);
        },
        async getOrders(){
        return (await dbPromise).getAllFromIndex('orders', 'purchaseDate').then((items) => {
            return items;
        })
     }
}
jakearchibald commented 5 years ago

This is a bug. Well spotted.

As a workaround, create a transaction:

// Instead of 
(await dbPromise).add('orders', order);
// Do this:
const tx = (await dbPromise).transaction('orders', 'readwrite');
const id = await tx.store.add(order);
await tx.done;
jakearchibald commented 5 years ago

Fixed in 2f24955fb63787faa118450092e02bc72d0929cd. Published in 4.0.1.