ALAB23
ALAB23

Reputation: 43

What could be causing transaction for indexeddb to not work in my code

var database = window.indexedDB.open("myTestDatabase", 3);

database.onerror = function(event) {
    alert('Error creating database');
}

database.onupgradeneeded = function(event) {
    var db = event.target.result;

    console.log(1);
    //
    if (!db.objectStoreNames.contains("data")) {
        //Add to indexDB
        db.createObjectStore("data", {
            keypath: "data"
        });
    }
}

//If the database is creaed run.
database.onsuccess = function(event) {
    var db = event.target.result;

    var transaction = db.transaction(["data"], 'readwrite');
    //More code here to store data into indexeddb
}

When running my code, I run into the following error: Uncaught NotFoundError: Failed to execute 'transaction' on 'IDBDatabase': One of the specified object stores was not found.

When looking at the indexeddb, the "myTestDatabase" is created, but the "data" objectstore is not. What might be the problem with this? It works sometimes, but other times it fails.

Upvotes: 3

Views: 1266

Answers (2)

Chukwujiobi Canon
Chukwujiobi Canon

Reputation: 3935

You can only add a new object store to an Indexeddb database during database upgrade: ie. onupgradeneeded.

Look at the modification as follows;

const createObjectStore = (
  database,
  objectStore,
  key,
  indexIsUnique = true
) => {
  const DB = indexedDB
  let request = DB.open(database)

  request.onsuccess = () => {
    let db = request.result
    if(!db.objectStoreNames?.contains(objectStore)) 
    {
      let newDBVersion = db.version + 1
      db.close()

      let newRequest = DB.open(database, newDBVersion)

      newRequest.onupgradeneeded = () => {
        let upgradedDB = newRequest.result
        try 
        {
          const collection = upgradedDB.createObjectStore(objectStore, { keyPath: key })
          collection.createIndex(key, key, { unique: indexIsUnique })
        } catch (error) 
        { throw new Error(error) }
      }
                    
      newRequest.onerror = (error) => {
        throw new Error(error)
      }
    }
  }

  request.onerror = (e) => {
    alert(e)
    console.log(e);
  }
}

I would also advice that you rewrite this function as an async function or as a Promise but this is totally up to you.

Upvotes: 0

Azaz Sayed
Azaz Sayed

Reputation: 63

Incrementing the version from 1 to 2, worked for me const openRequest = window.indexedDB.open('purple_score', 2);

Upvotes: 1

Related Questions