My current project involves setting up an indexeddb with multiple stores. It is essential to add initial data when creating these stores.
I have a function that handles the creation of the database and stores:
function db_setup(){
var request = indexedDB.open("db", "1.0");
request.onupgradeneeded = function(){
var db = request.result;
//Store 1
db.createObjectStore("store1", {keypath: "id", autoIncrement: true});
//Add initial data;
// Store 2
db.createObjectStore("store2", {keypath: "id", autoIncrement: true});
//...
//Store 3
// Initialize necessary databases
populateDatabase();
}
request.onsuccess = function (){
db = request.result;
populateDatabase();
}
}
Within the `populateDatabase` function, there are four other functions responsible for adding data to the stores:
function populateDatabase() {
initializeStore1();
initializeStore2();
//...
console.log("Database populated with data");
}
Each initialization function populates the stores using transactions like below:
var tx = db.transaction("store1", "readwrite");
var store = tx.objectStore("store1");
However, I'm encountering an issue where the initial data gets duplicated every time the page is opened or refreshed. They keep getting added repeatedly.
Adding `populateDatabase()` at the end of the `onupgradeneeded` function triggers an error:
Uncaught TypeError: Cannot read property 'transaction' of undefined
This error occurs on the line:
var tx = db.transaction ("store1", "readwrite");
The main goal is to create the data stores along with their initial data only once. Any suggestions on what might be causing this issue?
Thank you for your help in advance.