4
votes

I'm trying to add some values to an object store, getting this error in return (at line 22). The object store uses a keyPath 'id' and autoincrement: true.

function cacheObject(storeName, object) {
  return new Promise(function(resolve, reject) {
    let transaction = db.transaction([storeName], "readwrite");

    transaction.oncomplete = function(event) {
      console.log("Transaction complete");
      resolve(object);
    };

    transaction.onabort = function(event) {
      console.log("Transaction aborted: " + event);
      reject();
    };

    transaction.onerror = function (event) {
      console.log("Transaction error: "+  event.toString());
      reject();
    };

    let objectStore = transaction.objectStore(storeName);

    let objectReq = objectStore.add(object);
    objectReq.onsuccess = function (event) {
      console.log("saved object to idb: " + JSON.stringify(object));
    };
  });
}

Here is a sample from the onupgradeneeded event:

  req.onupgradeneeded = function (e) {
    let db = e.target.result;
    console.log("Running idb onupgradeneeded");
    if (!db.objectStoreNames.contains(STORY_STORE_NAME)) {
      let storyStore = db.createObjectStore(STORY_STORE_NAME, {keyPath: "id", autoIncrement: true});
      storyStore.createIndex('picture', 'picture', {unique: false});
      storyStore.createIndex('text', 'text', {unique: false});
      //more indexes created here
1
To be able to help better, can you put in the code where you actually run cacheObject? It will help tie your store name and object to the schemas you defined. - Ryan Dabler
Please share how you call the the function 'cacheObject'. I think it is important to pass an JavaScript object ( {...} ) to the object parameter (and no primitive value) - troYman

1 Answers

0
votes

I find the reason and solution

in short, the store.add value is not object({}), so the object.id = autoGeneratedId will raise error

in my case, I use

            database.createObjectStore(storeName, {
                keyPath: 'id',
                autoIncrement: true
            })

and use transaction get store

            store2.add(1)
            store2.add(2)

1.id = "val" will raise err

when i change it to store2.add({k: "v"}), it fix