Issue accessing array data in react-native

When attempting to retrieve data from a SQLite Database in React-Native (android), I encountered a peculiar issue. The function returns an Array with data, which is successfully logged to the console. However, when I attempt to log the length of the Array, it inexplicably prints "0".

Here are the functions:

getActByButton(category) {
        return new Promise((resolve) => {
            const activities = [];
            const request = 'SELECT activity FROM activity_button WHERE category = ? AND activity IS NOT NULL';
            this.initDB().then((db) => {
                db.transaction((tx) => {
                    tx.executeSql(request, [category]).then(([tx, results]) => {
                        //console.log('Query COMPLETED');
                        var len = results.rows.length;
                        for (let i = len; i > 0; i--) {
                            activities.push(results.rows.item(i - 1));
                        }
                        resolve(activities);
                    })
                }).then((result) => {
                    this.closeDatabase(db);
                })
            })
        })
    }

    getIconByAct(activity_ids) {
        return new Promise((resolve) => {
            const icons = [];
            const request = 'SELECT name, icon FROM activity WHERE id = ?';
            this.initDB().then((db) => {
                db.transaction((tx) => {
                    for (let id in activity_ids) {
                        tx.executeSql(request, [id]).then(([tx, results]) => {
                            console.log('Query COMPLETED');
                            var len = results.rows.length;
                            let icon = results.rows.item(0).icon;
                            let description = results.rows.item(0).name;
                            icons.push({ icon, description });
                        })
                    }
                    resolve(icons);
                }).then((result) => {
                    this.closeDatabase(db);
                })
            })
        })
    }

Function-call:

db.getActByButton(this.props.category).then((data) => {
    result_ids = data;
}).then(() => {
    db.getIconByAct(result_ids).then((data) => {
        console.log('DATA:');
        console.log(data);
        console.log(data.length);
        console.log(data[1]);
    })
})

Console: https://i.sstatic.net/0z3KT.jpg

Why is this happening? And how can I resolve it?

Answer №1

Give this a shot:

Retrieve the Activity by clicking on a button:

db.fetchActivityByButton(this.props.category).then((data) => {
    resultIDs = data;
}).then(() => {
    db.getIconByActivity(resultIDs).then((data) => {
        console.log(JSON.stringify(data));
        console.log(JSON.stringify(data.length));
    })
})

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

Can a single controller function in ASP.NET MVC4 be used to send back two arrays to the view?

Continuing from my previous query here, I am working with a model called SchoolTestsPerModulePerStudent which looks like this: public partial class SchoolTestsPerModulePerStudent { public long StudentID { get; set; } public long ModuleID { get; se ...

Altering pointer during drag操作

Is it feasible to customize the cursor during a drag operation? I've been exploring ways to achieve this for some time now. My goal is to replace the default 'not-allowed' cursor that appears when dragging an object with a different cursor. ...

substitute every item that is a part of a particular group

My current project involves creating an embedded widget. Users will be required to insert an anchor tag and JavaScript code on their page, which then dynamically renders content similar to how embedded tweets work. <a href="http://localhost:3000/user/1 ...

Alter the div's HTML content once the Ajax operation is completed

I have a div element that looks like this: <div class="progress" id="progress-bar"></div> I am using the following JavaScript code along with an ajax call to retrieve some data. The data returned is 0, however, the content is not being added ...

What are the steps to retrieve information from your personal server using Astro?

I have successfully set up a NodeJS server using Express and Astro for the frontend, with SSR configured through the Astro adapter for NodeJS. My current challenge is fetching data from the backend, and I am unsure of the correct approach to do so. Below ...

A class member is not permitted to include the 'const' keyword

Having trouble with my ts code as I try to create a constant that can be easily changed by just modifying a simple element - but keep encountering the error that says "A class member cannot have the 'const' keyword." Here's the code snippet ...

Determine the latitude and longitude coordinates of the edges of the ground overlay based on the data in the

I am trying to determine the corner coordinates in latitude and longitude of a ground overlay provided in a kml-file using either php or javascript. For example, I need to convert from: <LatLonBox> <north>60.406505416667</north> ...

What is the best way to retrieve the currently selected item from a Bootstrap filter/search feature?

I am currently working on implementing a filter and search feature using Bootstrap. The objective is that when the user searches for an item and the filter results in only one item remaining, if the user presses enter or "selects" the item, it should autom ...

Unable to get the deletion functionality to work for Dropzone.js and PHP script

I am currently using dropzone to handle file uploads. My goal is to delete the files on the server when the user clicks on the removeLink. I have implemented an Ajax function that calls a .php site for this purpose. However, I am facing an issue where I am ...

Whenever Sinon.stub() is invoked, it provides a unique value each time

Below is the code that I am currently writing tests for: 'use strict'; var internals = {}; var _ = require('lodash'); module.exports = { initialize: function (query) { internals.query = query; }, createField: fu ...

What is the process for creating a new object and saving it?

Exploring the AngularJS documentation, it appears that saving a new object is not as straightforward as expected. The $save method in $resource seems to only handle existing objects without any parameters. Is there a way to properly perform a POST request ...

Deleting a segment of content from a webpage

Currently, I'm in the final stages of completing a blackjack game. However, one aspect that I haven't implemented yet is the ability for the user to play again after finishing a round. My initial idea is to use a window.confirm dialog box, where ...

When accessing req.param on the server side in a Node.js application, it returns undefined

I am currently utilizing nodejs and angularjs for my project. In the client-side javascript file, I made a GET request to the nodejs server with necessary data in parameters. itinerary.js $http({ method : "GET", url : '/createItinerary&apo ...

Another exciting discussion on converting JSON to an HTML table

While I know that asking a question without providing any code is generally discouraged, I am feeling quite lost at the moment. I have some basic JSON files that follow a structure similar to the example below: [{ "key1" : "some value", "key2" : 1 ...

Creating a Yo Meanjs project seems like an insurmountable challenge

As I embark on this online tutorial journey, I encountered an issue. All the necessary installations and preparations have been completed, but when instructed to run 'yo meanjs', an error message appeared: https://i.sstatic.net/0dCB4.png Could ...

Learn the process of assigning the present date using the jQuery UI date picker tool

I am looking to implement the feature of setting the current date using Angular/Jquery UI date picker. I have created a directive specifically for this purpose which is shown below: app.directive('basicpicker', function() { return { rest ...

Is it possible to update a shadow field using the updateOne pre hook in mongoose?

Seeking guidance on utilizing the updateOne pre-hook in mongoose version 5.9.5. I am looking to establish a normalized 'shadow field' (not certain if this is the correct terminology) to aid in specific searches. Although I can successfully updat ...

Iterate through every row in the table in order to carry out a mathematical operation

I have created a jQuery function to add a table dynamically: $(document).on('click', '.add', function(){ var html = ''; html += '<tbody><tr>'; html += '<td><select name="product_name[]" cla ...

Can the store.dispatch method in Redux be considered synchronous or asynchronous?

This may seem like a simple question, but despite my efforts I couldn't locate the answer anywhere else. Can anyone clarify whether store.dispatch is synchronous or asynchronous in Redux ? If it is indeed asynchronous, is there a way to include a ca ...

Vanilla JavaScript Troubleshooting: Top Scroll Button Issue

Attempting to develop a Scroll To Top Button utilizing Vanilla JS, encountering errors in the dev console. Existing jQuery code that needs conversion to vanilla js Uncaught TypeError: Cannot read property 'addEventListener' of null My Vanilla ...