Exploring the power of indexedDB within a PhoneGap app

I am currently working on developing an offline application using PhoneGap and I need to integrate a local database for this purpose. In my index.js file, which loads the application, I have a global variable.

var db;

I have a controller that saves the database information in an indexedDB database when the user logs in, allowing them to use the application offline.

 //controller call
 Database.create(res.data.categories);

function Database() {

return {
    create: function (categoryDocs) {
        var request = indexedDB.open("kaldoa", 1);

        request.onsuccess = function (event) {
            db = event.target.result;
            console.log("DB loaded successfully");
        };

        request.onerror = function (event) {
            console.log(event)
        };

        request.onupgradeneeded = function (event) {
            db = event.target.result;
            console.log("DB initialized / created");

            //create collections
            db.createObjectStore("categories", {autoIncrement: true});

            //create documents
            var transaction = event.target.transaction;
            var categories = transaction.objectStore("categories");

            //add array objects to document
            categories.add(categoryDocs);

        };

    }
}

}

After checking in the Chrome inspector, the databases are successfully created and everything seems to be functioning well.

Next, I aim to display the stored data named 'categories' in another controller specifically designed for handling categories.

function categoryCtrl($scope, Category){

Category.browse().onsuccess = function (e) {
    $scope.categories = e.target.result.value;
};

}

However, I've encountered a problem where the data works fine in Chrome but fails to work in PhoneGap, throwing a console error:

Error: undefined is not an object (evaluating 'db.transaction')

This console error pertains to the services responsible for fetching the categories data.

function Category() {

return {
    browse: function () {
        return db.transaction(["categories"], "readonly").objectStore("categories").openCursor()
    }
}
}

I've spent the entire day trying to troubleshoot why it functions correctly in Chrome but not in PhoneGap. I understand that with the release of iOS 10 on September 29, 2016, Apple added support for both Safari and WebView.

indexeddb ios support

Answer №1

Avoid relying on a global database variable in this manner. It may not be initialized and ready for use when you try to access it, due to the nature of asynchronous code execution.

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

Ending a connection to MS SQL server in node.js with mssql library

In my journey to write a node.js script for querying an MSSQL database, I find myself navigating the realm of JavaScript, node.js, and VSCode with limited SQL knowledge. While I have managed to piece together working code, the issue lies in the connection ...

Automatic parsing and formatting of JSON object keys

My form is populated automatically using a script. Whenever the user selects an option from a dropdown, an AJAX request is triggered to an external file (which retrieves data from a database using json_encode) and populates the form fields. Here is the sn ...

Enhance and soften images using CSS with smooth responsiveness across all web browsers

When an image is clicked, it should zoom in and become the background of the page with a blurred effect. I attempted to achieve this using the following code... <style type="text/css"> body{ position: absolute; margin-left: 100px; right: 0; z-inde ...

Delay the execution of an AngularJs directive for later processing

I am seeking a way to delay the execution of a nested directive until after an asynchronous task is completed by its parent directive. While I can achieve this easily with two lines of jQuery, I am curious if there is a purely Angular approach using $q. Y ...

The functionality of jQuery typeahead ceases to perform after I choose an option from the dropdown menu

Initially, my jQuery typeahead autocomplete function works perfectly. However, after selecting an option from the list, it fails to show results when I try to use it again by typing in the input field. It seems like the typeahead functionality gets destro ...

Exploring the contents of an array in ReactJS

const rowData = this.state.market.map((market) => { console.log("details", market["info"]) { return { marketInfo: ( <div> {market && !!market["info"] ? ( <div> ...

Having trouble with jQuery events not triggering properly after dynamically inserting elements using an ajax request?

It's strange that all my jQuery events become unresponsive after an AJAX call. When I use a load function, once the JSP reloads, none of the events seem to work properly. Any suggestions? Below is the code that triggers the function call: $('#p ...

Tips for avoiding page reload when submitting a form with form.submit() in ReactJs

Is there a way to avoid the page from refreshing when triggering form submission programmatically in ReactJS? I have attempted to use this block of code: const myForm = () => <form onBlur={(e) => { if(!e.relatedTa ...

Building interactive web forms with real-time validation using CodeIgniter

I'm looking for a way to use ajax (jquery library) to validate my forms. Specifically, I have a form that requires a minimum password length of 6 characters. Currently, I have implemented the validation rule as follows, $this->form_validation-> ...

Separating a variable within a Twitch bot: techniques and tips

I am working on setting up a feature in my Twitch bot where it can respond to the command !test [var]. For example, if someone types !test @jeff, the bot would reply with hello @jeff. Currently, I am using tmi. client.on('chat', function(channe ...

Access JSON value using jQuery by key

Creating a JSON structure that contains information about attendees: { "attendees": [ { "datum": "Tue, 11 Apr 2017 00:00:00 GMT", "name": " Muylaert-Geleir", "prename": "Alexander" }, { "datum": "Wed, 12 Apr 2017 ...

What steps can I take to ensure my customized tab component can successfully pass an index to its children and effectively hide panes?

I'm currently working on developing a custom Tabs component to enhance my knowledge of React, but I seem to have hit a roadblock. The structure involves three key components that draw inspiration from Material-UI tabs: Tabs, Tab, and TabPane. Tabs.j ...

Incorporating TypeScript with jQuery for efficient AJAX operations

I recently added jQuery typings to my TypeScript project. I am able to type $.ajax(...) without encountering any compile errors in VS Code. However, when I test it on localhost, I receive an error stating that "$ is not defined." In an attempt to address t ...

Creating a dynamic multi-select feature in AngularJS with ng-repeat

I'm relatively new to AngularJS and JavaScript, but I've managed to create a functional multi-select list. The ng-model linked to the dropdown is part of a "user" DTO object, specifically a property that stores an array of "groups" the user can j ...

Unveiling the secret to organizing messy code in node_modules for better readability in React applications

When I need to access files in node modules, I often come across compressed code that is difficult to read. My prettier formatter doesn't seem to format these files. Is there a way to clean up the raw code and make it more readable, similar to regular ...

Revise the calculation output when a specific input is missing

As I work on creating a basic web page for computing values based on selected options, I've encountered an issue with the calculation process. The result does not immediately appear; instead, I have to input a value like 0 and then delete it in order ...

Tips for incorporating ajax to load a new webpage into a specific div container

I have a website with two pages. I want to load Page 2 into a div on Page 1 and then display Page 2 when clicked on. I'm attempting to implement the following code, but it doesn't seem to be working for me. As a beginner, I apologize if this is a ...

Using Angular 2 HTTP to retrieve a list of file names from a Node backend directory

I am currently attempting to establish a connection between an Angular 2 frontend and a Node/Express backend using an HTTP GET request. The backend should respond by providing a list of file names from a specific folder using the fs.readdir method. I have ...

Google Maps JavaScript API failing to load due to a 403 error after the tab has been open for an extended period

Our website utilizes Angular and includes tabs with Google Maps that load lazily when needed. Everything works fine when the page is first opened, but after spending some time on a tab without a map, switching to a new tab with a map results in the map not ...

Tips for integrating custom code into your Angular cli service worker

Although I have successfully generated and configured the service worker using a config file generated by Angular CLI, I am struggling to find documentation on how to add custom code to the ngsw-worker.js file. I want to include functions such as push no ...