Levi Daniels
Levi Daniels

Reputation: 1

Why does my IndexedDB save function not work?

I am making an edge web extension game, I've got the game done, so now i have to do storage. I will use IndexedDB because webSQL will no longer be available soon. I made a save function, but i got an error.

This is the function that calls the save function every 2 seconds:

function init() {
  const data = { 
  money: money, 
  monkey: monkey 
  };
  setInterval(function() {
  saveGameData("myDatabase", "store", data); }, 2000);
}

And this is the save function:

function saveGameData(databaseName, storeName, data) {
  // Open the database
  const request = indexedDB.open(databaseName, 1);
  
  request.onerror = function() {
    console.error("Database error:", request.error);
  };
  
  request.onsuccess = function() {
    const db = request.result;
    
    // Start a transaction and get the object store
    const transaction = db.transaction(storeName, "readwrite");
    const objectStore = transaction.objectStore(storeName);
    
    // Save the data to the object store
    const saveRequest = objectStore.put(data);
    
    saveRequest.onerror = function() {
      console.error("Error saving data:", saveRequest.error);
    };
    
    saveRequest.onsuccess = function() {
      console.log("Data saved successfully");
    };
  };
}

And this is the error i get:

Uncaught NotFoundError: Failed to execute 'transaction' on 'IDBDatabase': One of the specified object stores was not found.

The error is from this line: const transaction = db.transaction(storeName, "readwrite");

Upvotes: -1

Views: 128

Answers (1)

Kendrick Li
Kendrick Li

Reputation: 3151

It looks like you have missed the onupgradeneeded event. For more information, you can refer to this doc.

If you have already called onupgradeneeded event, try changing the version number.

Upvotes: 0

Related Questions