convert data from IndexedDB to a JavaScript array

Hello, I am quite new to web development and currently experimenting with creating an "offline" application using vue.js and dexie.js. Dexie.js provides easier access to Indexed Database on modern browsers.

However, I believe my issue lies more in the basic JavaScript realm.

I have set up this simple DB (enhanced with Dexie):

var db = new Dexie("appDatabase");
db.version(1).stores({
   tasks: '++id,name, agi, str, vit, int',
   player: 'id, name, agi, str, vit, int',
});

(only one player is allowed)

...and I have successfully managed to edit and add data into the indexedDB; now I am attempting to transfer data from IndexedDB to an array for better visualization within Vue.js.

        transferDBtoArray() {
            db.tasks.where('name').noneOf().toArray(function(result) {
                for(var i= 0; i< result.length; i++) {
                    app.tasks[i].id = result[i].id;
                    app.tasks[i].name = result[i].name;
                    app.tasks[i].str = result[i].str;
                    app.tasks[i].int = result[i].int;
                    app.tasks[i].vit = result[i].vit;
                    app.tasks[i].agi = result[i].agi;
                    
                }
            });

Here is the structure of my array within the Vue app:

        tasks : [
            {id: 0, name:"", str: 0, agi: 0, int: 0, vit: 0}
        ],

Unfortunately, it is not working as expected:

Unhandled rejection: TypeError: Cannot set property 'name' of undefined

I am aware that accessing data from the DB works fine:

        test() {
            db.tasks.where('name').noneOf().toArray(function(result) {
                for(var i= 0; i< result.length; i++) {
                    console.log( result[i].name);
                    console.log( result[i].agi);
                    console.log( result[i].str);
                    console.log( result[i].int);
                    console.log( result[i].vit);
                }
            });
        },

I suspect that my mistake lies in the way I structured the array, but I am not entirely sure...

Any help would be greatly appreciated. Kind regards,

Richard

Answer №1

Ensure that app.tasks[i] is assigned as an empty object at the start of each iteration within the loop:

    transferDBtoArray() {
        db.tasks.where('name').noneOf().toArray(function(result) {
            for(var i= 0; i< result.length; i++) {
                app.tasks[i] = {};
                app.tasks[i].id = result[i].id;
                app.tasks[i].name = result[i].name;
                app.tasks[i].str = result[i].str;
                app.tasks[i].int = result[i].int;
                app.tasks[i].vit = result[i].vit;
                app.tasks[i].agi = result[i].agi;
                
            }
        });

Alternatively, a more concise approach can be used:

transferDBtoArray() {
  db.tasks.where('name').noneOf().toArray(results => results.map(result => ({          
        id: result.id,
        name: result.name,
        str: result.str,
        int: result.int,
        vit: result.vit,
        agi: result.agi,
  })));

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

Python script to read an unspecified number of columns containing numerical data

Typically, my python script is designed to read data from stdin and write it to stdout. However, if specific command line options are specified, the script can read from a file and/or write to a file. In this case, the script will exclusively read two col ...

Is it possible for me to clear the content of the previous page before the page above it slides

Using the ons-sliding-menu component from Onsen UI, I have encountered an issue. When clicking on a menu item in the behind-page, the above-page slides in but still displays the previous content for a brief moment (although very short, it is noticeable). ...

React/Redux does not retain previous items with Infinite Scroll

I am currently facing an issue where the new set of items loaded from the reddit API using Infinite scrolling overrides the previous items when the user scrolls to the bottom of the page. Although the new items load successfully, they replace the existing ...

Implementing the insertion of data using array pointers

I am currently working on a program that adds records to a basic phone book. The code I have written so far seems to have an issue - the function stops and gets stuck at declaring struct record x, causing my added record not to display properly and ultimat ...

Using jQuery to retrieve the id with [id^=''] when making an AJAX request, then populating and generating a table based on the retrieved data

In my jQuery code, I am using AJAX to fetch data and then creating a simple table with that data. Here is an example: $.ajax({ method: 'GET', url: '/analyzePage/searchTag/' + tagName, contentType: false, processData: fa ...

Open Browser in VSCode using Vite - A Quick Shortcut

Currently, I am utilizing Vue and Vite in VSCode on a Windows 10 system. Within my project setup, I have integrated NPM Scripts shortcuts to streamline the building process. To enhance my workflow, I implemented the following key binding configuration in k ...

Managing the output from a function: Tips and strategies

Below is the function I am currently working with: function kontrola(){ var jmeno = self.document.forms.newPassForm.user.value; $.get("checkMail.php?mail="+jmeno, function(data){ if(data=='1'){ alert('Tento ...

Vuejs modal is automatically closing upon form submission, regardless of any errors present

I recently implemented validation using vuelidate for my form, however, I encountered an issue where the modal would close even if there were errors present. My tech stack includes Bootstrap-Vue alongside VueJs. I aim to keep the modal open in case of an ...

Attach an event to the HTML document's element and utilize addEventListener on the same element

What sets apart the logical/programming difference? I found myself responding to a duplicated question and decided to change one of the repetitive answers with a fresh perspective (in my opinion, even though it appears longer): for (i = 1; i <= 10; i++ ...

tsc failing to generate the distribution folder

I've encountered a strange issue with compiling my TypeScript project into the ./bin folder. The tsc command runs without any errors, but nothing is actually being created in the designated folder. It's puzzling me and I can't seem to figure ...

How can you determine if all elements in an array are the same or different using C++? Additionally, how can you retrieve and display all unique elements that appear at least once in the

How can I determine if all elements of an array are equal? For example: 1 2 3 Output: NO Example 2: 2 2 2 2 Output: YES I attempted to solve this issue using the code below, but it always outputs "NO": # include < iostream > using ...

Retrieving Memory Usage of a Process in Node.js/JavaScript

I'm currently exploring ways to access the memory of a running process. For my web application, I have a server built with Node.js, an app.js file, and an agent that communicates with app.js through the server. I'm interested in finding a metho ...

Tips for transforming a nested foreach loop for a category tree into recursive function

I am looking to convert this nested loop into a recursive function because I am unsure of the depth of the category tree. Here is the original PHP code: $categories = []; function processCategories($category_tree, $prefix = '') { foreach ($ ...

Ways to trigger a function when the store contains data

I'm tasked with creating a video player object, but I need the stream object to be available prior to instantiating the video player. The this.stream variable is populated by vuex data store. However, I've noticed that the mounted() and created( ...

Issue with RequireJS: The data-main attribute fails to load the specified file

As I convert my small project into nodejs, I am facing an issue with the requireJS file that defines the JS to be used in the project not loading properly. Below is the structure of my project: https://i.sstatic.net/oYnqn.png The ng-app specifies the fr ...

Can I keep using ng-repeat multiple times in my code?

Working on a AngularJS application that involves handling a complex JSON file with multiple nested arrays and objects. My query is: Is it appropriate to use ng-repeat repeatedly for accessing the data from the JSON? <div ng-repeat="parent in parents"&g ...

Speed Up Loading of Arrays with While Loop Alternative

I am currently working with a small array that fetches data from Twitch.tv and uses variables to display it. The array is created to hold this information. <?php include 'header.php'; $streamers = array("NomadicTV","TheOneJat","greatbritish ...

Looking for a pattern that combines Browserify and Angular?

Currently, I am embarking on a project using angular and browserify for the first time. I am seeking advice on how to properly utilize the require function with browserify. There are multiple ways to import files, but so far, I have experimented with the ...

I am experiencing an issue with my localhost website where the images only display after I open the files in VScode. Is there a way to load the images correctly using app.js?

app.js While working on web development in VScode, I've encountered an issue where the images on my localhost website only appear after opening files like home.pug and contact.pug alongside app.js. Is there a way to make the images load properly witho ...

Issue with Ionic 2: Variable is altered but does not reflect in the HTML view

Hello everyone, I am new to the world of ionic 2 and I am facing a problem that I hope you can help me with. I have a variable that I want to display on my smartphone screen by placing it between {{ myVar }} in my HTML code. The initial display works fine, ...