Search code examples
javascriptindexeddbdexie

How do I check if a store key exists in IndexedDB?


I want to check and update quantity of item in indexeddb store if it already exist. This how I current add item to the store using Dexie

    async function addNfetch (itemdata) {
        
        return new Promise((resolve, reject) => {
         db.table('cartitems')
        .add(itemdata)
        .then(() =>{ 
            db.table("cartitems").toArray().then((itemArry) => {
                console.log("item array ", itemArry)
    
                resolve(itemArry)
             })
        })
        .catch(error => {
            console.log(error);
          });
    
      })
    }

the above function only adds and throws an error if the object key already exist

DexieError {_e: Error at getErrorWithStack (http://localhost:3000/static/js/0.chunk.js:14551:10) at new Dex…, name: "ConstraintError", message: "Key already exists in the object store.↵ ConstraintError: Key already exists in the object store.", inner: DOMException: Key already exists in the object store., _promise: DexiePromise,

to check if a key exist I can only think of using the error.message.

  if (error.message == "Key already exists in the object store"){
     // then object exist 
  }

Is there a better way to check if store key already exist so that i can update instead of overwritting it.


Solution

  • function addNfetch (itemdata) {
      return db.table('cartitems').put(itemdata);
    }
    

    put() is like add() but updates the entry if it already exists.

    Also, just a side note: You don't need to create new Promise() to call promise based API:s. This example doesn't need to be async as it only calls a single API method. It could equally be:

    async function addNfetch (itemdata) {
      return await db.table('cartitems').put(itemdata);
    }
    

    But as you see, in this sample it doesn't really simplify anything.