What could be causing the IndexDB to overlook my totalMoney object Store?

If you're new to Index DB, you might be facing a simple fix issue that's not in your code. Utilizing live server for display, the error you encounter is regarding the total Money not displaying as expected in the HTML, generating a console error: Here. Your attention to this matter is appreciated.

Below is the content of my dbFunctions.js file:

let db;
let request = indexedDB.open("financeManager", 1);
...

Below are the addIncome.js and addIncome.html files respectively:

const dropdownIncome = document.getElementById("dropdownIncome");
const optionForms = document.querySelectorAll(".options");
//submit btns form
const submitOneTime = document.getElementById("submitOneTime");
const submitMonthly = document.getElementById("submitMonthly");
const submitInterest = document.getElementById("submitInterest");
...
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <select id="dropdownIncome">
        <option value="default">--</option>
        <option value="optionOneTime">
            One-Time Income
        </option>
        <option value="optionMonthly">
            Monthly Income
        </option>
        <option value="optionInterest">
            Interest Income
        </option>
    </select>
    ...
</body>
</html>

Next up are the addExpenses.js and addExpenses.html files:

const dropdownExpenses = document.getElementById("dropdownExpenses");
const optionForms = document.querySelectorAll(".options");
//submit btns form
const submitMonthly = document.getElementById("submitMonthly");
const submitOneTime = document.getElementById("submitOneTime");
const submitMortgage = document.getElementById("submitMortgage");
...
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href = "addExpenses.css">
    <title>Document</title>
</head>
<body>
    ...
</body>
</html>

Finally, the financetracker.js, .css, and .html files:

//input daily expenses, includes consistent expenses as well as one-time purchases...
document.addEventListener("DOMContentLoaded", function(){
    var totalMoney = 10000000;
    checkAndInitializeTotalMoney(totalMoney);
    ...
.viewButtons{
    width: 350px;
    height: 200px;
    font-size: 50px;
    font-family: 'Times New Roman', Times, serif;
    border-radius: 10px;
}...
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="financetracker.css">
</head>
<body>
    <div class="balanceBottomLine">
    ...
</body>
</html>

Answer №1

There was an issue with the db variable in the dbFunctions.js file, appearing as undefined in the checkAndInitializeTotalMoney() method.

To resolve this:

You can address this by utilizing Promise and await constructs to ensure that the db is accessed prior to executing the checkAndInitializeTotalMoney() method. This serves as the initial solution.

In the context of:

dbFunctions.js AND finanstracker.html:

let db;
let request = indexedDB.open("financeManager", 1);


function openDb() {
    return new Promise((resolve, reject) => {
        request.onupgradeneeded = function(event) {
            db = event.target.result;
            db.createObjectStore("expenses", { keyPath: 'id', autoIncrement: true });
            db.createObjectStore("incomes", { keyPath: 'id', autoIncrement: true });
            db.createObjectStore("totalMoney", { keyPath: 'id', autoIncrement: true });
            if (!db.objectStoreNames.contains("totalMoney")) {
                
            }
        };

        request.onsuccess = function(event) {
            db = event.target.result;
            console.log("is db ok: " + db);
            resolve(db); //if db open success then accept and return
        };

        request.onerror = function(event) {
            console.log('error', event.target.errorCode);
            reject(event.target.errorCode); 
        };
    });
}

async function init(totalMoney) {
    try {
        await openDb();
        checkAndInitializeTotalMoney(totalMoney);
    } catch (error) {
        console.error("When db try to open error: ", error);
    }
}


function initializeTotalMoney(total){
    var transaction = db.transaction(['totalMoney'], 'readwrite');
    var objectStore = transaction.objectStore('totalMoney');

    var totalMoney = {
        'total': total
    };
    var request = objectStore.add(totalMoney);

    request.onsuccess = function(event){
        console.log("Successfull");
    }

    request.onerror = function(event){
        console.log("error adding total:" ,event.target.error);
    }
}

function checkAndInitializeTotalMoney(InitialValue) {

  console.log("db: " + db)

  var transaction = db.transaction(['totalMoney'], 'readonly');
  var objectStore = transaction.objectStore('totalMoney');

  var getRequest = objectStore.get(1);

  getRequest.onsuccess = function(e){
      if (!e.target.result){
          initializeTotalMoney(InitialValue);
      } else{
          console.log("totalMoney already initialized: ", e.target.result);
      }
  };
  getRequest.onerror = function(e){
      console.log("Error checking tot money: ", e.target.error);
  };


}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0>
    <title>Document</title>
    <link rel="stylesheet" href="financetracker.css">

Then proceed to call the init() method in financetracker.js like so:

document.addEventListener("DOMContentLoaded", function() {
    var totalMoney = 10000000;
    init(totalMoney);
});

An alternative approach would be:

If aiming for a simpler structure, consider opening the db before each operation and performing actions accordingly.

dbFunctions.js:

    let db;
    let request = indexedDB.open("financeManager", 1);

    request.onupgradeneeded = function(event){
        
        db = event.target.result;
        db.createObjectStore("expenses", { keyPath:'id', autoIncrement: true});
        db.createObjectStore("incomes", {keyPath: 'id', autoIncrement: true});
        db.createObjectStore("totalMoney", {keyPath: 'id', autoIncrement: true});

        
        if (!db.objectStoreNames.contains("totalMoney")) {
        }
    };

    request.onsuccess = function(event) {
        db = event.target.result;
        console.log("is db ok: " + db);
    
    };

    request.onerror = function(event) { 
        console.log('error', event.target.errorCode);
    };

    //should only be used once, adds totalMoney as a db 
    function initializeTotalMoney(total) {
        var transaction = db.transaction(['totalMoney'], 'readwrite');
        var objectStore = transaction.objectStore('totalMoney');

        var totalMoney = {
            'total': total
        };
        var request = objectStore.add(totalMoney);

        request.onsuccess = function(event) {
            console.log("Successfull");
        }

        request.onerror = function(event) {
            console.log("error adding total:" ,event.target.error);
        }
    }

    function checkAndInitializeTotalMoney(db, InitialValue) {
        //OPEN HERE AGAIN
        const request = window.indexedDB.open("financeManager");
        request.onsuccess = (event) => {
            const db = event.target.result;
            console.log("db: " + db)

            var transaction = db.transaction(['totalMoney'], 'readonly');
            var objectStore = transaction.objectStore('totalMoney');

            var getRequest = objectStore.get(1);

            getRequest.onsuccess = function(e) {
                if (!e.target.result) {
                    initializeTotalMoney(InitialValue);
                } else {
                    console.log("totalMoney already initialized: ", e.target.result);
                }
            };
            getRequest.onerror = function(e) {
                console.log("Error checking tot money: ", e.target.error);
            };
        }
    }

Then invoke the init() method in financetracker.js as follows:

document.addEventListener("DOMContentLoaded", function() {
    var totalMoney = 10000000;
    checkAndInitializeTotalMoney(totalMoney);
});

Upon implementing either of these solutions, observe the console output:

https://i.sstatic.net/GSnx6.png

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

CSS - Discovering the reason behind the movement of text post generation (animation)

I have a question regarding CSS animation, specifically the typewriting effect. I was able to successfully achieve the typewriting effect using animation. However, I noticed that even though I did not set any animation for transforming, once the text is g ...

What is the best way to incorporate vertical lines into a set of progress bars?

I want to create progress bars with vertical lines representing specific steps within the progression. While I can display progress bars, I am unsure how to incorporate these vertical lines. Does anyone have any suggestions or ideas on how to achieve this? ...

React.js: The art of nesting components within each other

One common feature in many template languages is the use of "slots" or "yield" statements, which allow for a form of inversion of control by wrapping one template inside another. Angular offers the "transclude" option for this purpose. Ruby/Rails utilize ...

The JavaScript "sort()" method outlined in the Mozilla Documentation specifically created for the sorting of numbers

When it comes to sorting numbers in JavaScript, we can utilize the sort() function with a specific trick that yields perfect results. The tip for successful number sorting is as follows: [12, 2, 23, 3, 43, 54].sort(function (a, b) { return a - b ; } ) S ...

"Removing the default background color in the latest version of next.js: A step-by

Check out this screenshot for reference Whenever I change the gradient color in next.js, it defaults to these lines. However, switching to a blue or green color fixes the issue. The problem arises when using my current background color code: background: ...

Creating a unique Angular 2 Custom Pipe tutorial

I've come across various instances of NG2 pipes online and decided to create one myself recently: @Pipe({name: 'planDatePipe'}) export class PlanDatePipe implements PipeTransform { transform(value: string): string { return sessionStor ...

Choose key and value pairs in AngularJS

Currently, I am retrieving JSON values from an HTTP service for each ID and attempting to create a dropdown with a list of names and IDs as keys to store. Below is the HTML code snippet: <select> <option ng-repeat="(key, value) in data" value="{{ ...

Upon implementing a catch-all express routing solution, the Fetch API calls are no longer successful. The error message received is "Unexpected token < in JSON at

While working on a React project, I encountered an issue outlined in this link: React-router urls don't work when refreshing or manually typing. To resolve this problem, I decided to implement the "Catch-All" solution recommended in that discussion. ...

How to create a full-page background image using Bootstrap?

Take a look at this example: In the provided example, there is a background landing page that expands to fit the width of the viewport, remains responsive, and does not take up the full width of the page. How can you utilize bootstrap to manually code an ...

Event binding done correctly

I need some clarification on proper event binding. I pasted my JavaScript code here, and someone mentioned the following: PROPER EVENT BINDING: Instead of using methods like .click(), .bind(), or .hover(), consider using the preferred .on() method. $( ...

Adjust the color of input labels using jQuery validate

I have a form where I want to change the class of the input labels when a specific field fails validation. My goal is to add the 'error' class to the spans that are directly above any invalid form elements. Here is an example of my HTML structur ...

What is the best way to stack div elements one after the other?

I am a complete beginner in HTML and I have a project for my web design class about a movie. http://jsfiddle.net/Lbo1ftu9/ <div id="footer"> <a href="D:/MOVIE REPORT/akira.htm" title="GO BACK?"><img src="D:/IMAGES/goback.gif"> My code ...

Creating padding for a Drawer component in Material-UI with React JS

I'm struggling to set a marginTop for my Drawer within the Drawer class component. Here's the code I've been working with: const theme = createMuiTheme({ root: { marginTop: '40px' }, }) class PageMenu extends React ...

Is it possible to invoke a Node.js function within PugJS?

I am looking to implement a clickable button in PugJS that triggers JavaScript code within Node.js. views/index.pug doctype html html head title #{title} link(rel='stylesheet', href='/css/style.css') meta(name="viewp ...

I'm a beginner in jest and I'm curious, how should I go about writing a test for this

Below is a method I have called onViewed: onViewed() { const { current } = this.state; this.slides[current] = { ...this.slides[current], viewed: true }; const filtered = _.filter(this.slides, slide => slide.section === this.slides[current].s ...

Angular project experiencing issues with Bootstrap integration

I recently integrated the bootstrap navbar into my Angular project. Here is the process I followed to install it: Installed Bootstrap and jQuery using the CLI: npm install bootstrap jquery --save https://i.sstatic.net/UoZIa.png angular-cli.json: "st ...

Adjust the size of fonts for elements that are added dynamically

My goal is to dynamically add elements with decreasing font sizes to a fixed-width/height container until they no longer fit. I've managed to scale the font based on the browser window size, but that's not the intended solution. Is it possible t ...

Bootstrap select box gracefully fits within a dynamically adjusting height div

Can someone help me troubleshoot the issue with displaying/overflowing the .drop-down outside of the .item box in this demo? I need to keep the height of the .item as auto but for some reason, I can't enable overflow visible on it. .item{ backg ...

Expand the width of the image gradually until it reaches its initial size within a flexible DIV container

I am working with a <div> container that occupies 80% of the screen on a responsive page. Within this <div>, I am attempting to display an image that is sized at 400 x 400 pixels. My objective: As the screen width increases: The <div> ...

There seems to be an issue with the item display page when clicking on the 'view details' button within the Bootstrap tab

Encountering a problem with displaying the product details page. There are four bootstrap tabs, each containing some Product Items with a Quick View link button. The issue arises when clicking on the link button, as all tab items with the same ID are displ ...