Implementing a one-time addition of initial data in indexedDB

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.

Answer №1

When upgrading in indexedDB, data insertion is not allowed during the upgrade event. The recommended approach is to close the connection after the upgrade and reopen it for inserting data.

The process should follow these steps:

function db_init() {
  var request = indexedDB.open("db");
  var dbShouldInit = false;
  request.onupgradeneeded = function(e) {
    var db = e.target.result;
    dbShouldInit = true;

    // Create store1
    db.createObjectStore("store1", {
      keypath: "id",
      autoIncrement: true
    });
    
    // Add initial datas

    // Create store2
    db.createObjectStore("store2", {
      keypath: "id",
      autoIncrement: true
    });

  }
  
  request.onsuccess = function(e) {
    e.target.result.close();
    if(dbShouldInit)
      db_populate(); 
  }

}

function db_populate() {
  init_store1(init_store2); 
}

function init_store1(callback) {
  var request = indexedDB.open("db");
  request.onsuccess = function(e) {
    var db = e.target.result;
    var tx = db.transaction("store1", "readwrite");
    var store = tx.objectStore("store1");

    // Initialize store1
    
    tx.oncomplete = function(e) {
      callback(); 
    };
  }
}

function init_store2() {
  var request = indexedDB.open("db");
  request.onsuccess = function(e) {
    var db = e.target.result;
    var tx = db.transaction("store2", "readwrite");
    var store = tx.objectStore("store2");

    // Initialize store2

    tx.oncomplete = function(e) {
      // App can continue from here 
    };
  }
}

Answer №2

(function () {
  // Uncomment the following line to delete the "store" database
  //indexedDB.deleteDatabase("store");
  
  var openDB = indexedDB.open("store", 1);
  
  openDB.onupgradeneeded = function () {
    var db = openDB.result;
    var store;
    
    if (!db.objectStoreNames.contains("example")) {
      store = db.createObjectStore("example", {keyPath: "some"});
      store.put({some: "initData"});
    }
  };
  
  openDB.onsuccess = function (e) {
    var db = e.target.result;
    
    var rqst = db.transaction("example", "readonly")
                 .objectStore("example")
                 .get("initData");
                 
    rqst.onsuccess = function (e) {
      console.log(rqst.result);
    };
  };
})();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to sort the values of an associative array in JavaScript?

Consider the following associative array: array["sub2"] = 1; array["sub0"] = -1; array["sub1"] = 0; array["sub3"] = 1; array["sub4"] = 0; How can you efficiently sort this array in descending order based o ...

Importing XML data into a JavaScript variable using jQuery without displaying an alert message

Despite previously asking questions about loading XML into a JS variable, I haven't found a satisfactory solution. In my script, I declare a variable before making an ajax request and then assign the result to that variable. However, this only seems t ...

Toggle the visibility of divs using jQuery for easy filtering

I am looking to enhance my filtering system by allowing users to apply and view multiple filters simultaneously. For example, I want to be able to select 'High' and 'pizza' filters and see the results that match both criteria. Currently ...

When the ESC key is pressed during a keyup event, the value of event.which is determined to be

On my ASP.Net master page, I've implemented this jQuery code: jQuery(document).keypress(function(event) { alert('keypress() called. e.which = ' + event.which); if (event.which == 27) { jQuery(this).trigger(&a ...

Executing Windows cmd.exe commands from JavaScript code running on Node bash - A step-by-step guide

Is there a method to integrate a windows batch file within JavaScript code? Or is there a more secure approach to accomplish this using a node package? scripts.bat ECHO "JAVASCRIPT is AWESOME" PAUSE scripts.js // Code for executing the batch file // I ...

Ensuring the consistency of actions through thorough testing

Currently utilizing xstate for the implementation of a login flow. Within my machine, the initialState triggers a Promise, which redirects to a state with an entry action if rejected. I am seeking to properly test the timing of when this action is called. ...

The scroll() function in jQuery does not bubble up

Recently, I encountered an issue with a Wordpress plugin that displays popups on scroll. The code I currently have is as follows: jQuery(window).scroll(function(){ //display popup }); The problem arises with a particular website that has specific CSS ...

Retrieve information from a server using a REST API and populate a Multiple Select Picker in a React Native application

I am currently utilizing the REST API to retrieve server data, with the intention of populating a multiple select picker in React Native. However, I have encountered an error while attempting to achieve this task. Below is the response received from the se ...

Perform a Fetch API request for every element in a Jinja2 loop

I've hit a roadblock with my personal project involving making Fetch API calls to retrieve the audio source for a list of HTML audio tags. When I trigger the fetch call by clicking on a track, it always calls /play_track/1/ and adds the audio player ...

Is JavaScript the go-to solution for rearranging a list of objects?

I have come across a data structure related question that I believe would be best addressed in this forum. Recently, I have been encountering the following issue frequently. I receive data from a service in the following format. It consists of an array of ...

Instructions on incorporating a logical condition for an object that is entering a region in motion

I am currently in the process of developing a new game concept. The goal of the game is to maneuver a square across the screen while avoiding raindrops that fall from the top of the canvas. I need assistance with programming the logic so that when a rain ...

What is the best method for finding the value of an element?

Here is the snippet of code that I'm working with: if($('span').text().indexOf("t")){ console.log($('span').text()); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <sp ...

Using codeigniter and JQuery, I have developed a unique Javascript function to selectively extract a specific portion of text

I'm currently working with the following syntax: $("#orderbynumber").autocomplete( { source: "get_orders_by_order_number", messages: { noResults: '', results: function() {} }, select: function( event, ui ) { var select ...

Is there a way to use the property of an object to perform a merge sort, rather than relying on an Array?

Query About Sorting JSON Object in JavaScript In search of the most efficient method to sort a large JSON object based on a specific property, I turned to JavaScript. My initial thought was to utilize a merge sort algorithm for this task due to its speed. ...

Prevent AngularJS from entering endless digest loops by incorporating unpredictable content

One of the main components in my structure is an <img ng-repeat="img in api.images" src="{{ img.url }}"> The api object contains a list of image IDs and needs to make HTTP calls to retrieve the URLs for each image ID from the server. However, these ...

Could the issue of picture elements not rendering be due to using identical IDs on multiple pages?

Currently, I am in the process of developing a 6-page website. I have completed the template for the navigation elements, but there seems to be an issue. After moving the CSS and JavaScript into external files for elements that will remain constant across ...

Using Selenium WebDriver to wait for a JavaScript-generated table to be fully loaded and visible

My current challenge involves scraping data from the table of a specific F5 Article (). Sometimes, I am able to successfully extract the tables from the DOM, while other times, the JavaScript-generated tables are not being crawled. Despite my attempts with ...

The AngularJS $rootscope $destroy event is not being triggered, resulting in timeouts not being cancelled

Below is the code snippet that I am currently working with: function initialize() { var defer = $q.defer(); var deferTimer = $q.defer(); var cancelTimeout = $timeout(function() { if (defer !== null) { ctrlr.setProcessingParameters('X ...

"Unlocking the Power of Facebook with Javascript and Ajax

My Cordova app successfully authenticates with Facebook, but when trying to retrieve data, I encounter errors. I suspect there may be an issue with my URL. Can anyone identify a mistake in this? Errors: app: makeAPICalls: error:setting authenticatedUser ...

Identification of inappropriate language in usernames

One of the challenges I'm facing is detecting inappropriate language in usernames. Currently, I am using regex to validate the username based on a specific pattern: "/^[A-Za-z0-9]*(\d*\.\d*)*[A-Za-z0-9]+$/" This regex pattern allows u ...