Looking to retrieve information from a database transaction in a React Native application

I am new to working with React Native and I am facing an issue in my main component where I am trying to execute a database query and retrieve the data. However, when I run it, the console logs 'undefined'. Can anyone help me solve this problem? Thank you.

Here is my main component:

const fetchData = async () => {
    let queryselect = 'SELECT * FROM tbl_messages ';
    var result = await selectData(queryselect);

    if (result === false) {
        console.log('no data');
    } else {
        console.log(result);
    }
}

In my database component:

var db = openDatabase({ name: 'message.db', createFromLocation: 1 });

db.transaction(tx => {
    tx.executeSql(
        query,
        [],
        (tx, results) => {
            var len = results.rows.length;
            if (len === 0) {
                console.log('no records found');
                return false;
            } else {
                var temp = [];
                for (let i = 0; i < results.rows.length; ++i) {
                    temp.push(results.rows.item(i));
                }
                return temp;
            }
        }
    );
});    

}

Answer №1

Here is a code snippet demonstrating the use of Promises:

export const fetchData = () => {
    return new Promise((resolve, reject) => {
        db.transaction(tx => {
            tx.executeSql(
                query,
                [],
                (tx, results) => {
                    var len = results.rows.length;
                    if (len == 0) {
                        console.log('No data found');
                        resolve(false);
                    } else {
                        var temp = [];
                        for (let i = 0; i < results.rows.length; ++i) {
                            temp.push(results.rows.item(i));
                        }
                        resolve(temp);
                    }
                }
            );
        });
    });
}

};

Also, here's an example of how to read and set results using React hooks:

const [data, setData] = useState([]);

const fetchDataAndSetData = async () => {
    const results = await fetchData();
    console.log(results)
    setData(results);
}

useEffect(() => {
    fetchDataAndSetData();
}, []);

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

There seems to be an issue with the package not running at xxx:yy in React

As I work on developing a standalone Android app using React Native, the installation of react-native-fcm has led to a persistent error message appearing: The Gradle file in my project appears as follows: // Top-level build file where you can add configu ...

When changing recipients in Firebase, the Javascript code fetches the same message multiple times even though there is only a single message stored in the database

In the process of developing a chat application using Firebase and JavaScript, I have come across an issue. Whenever I switch receivers multiple times, the message I send is fetched multiple times even though it is only sent once to the database. var selec ...

Having trouble displaying the accurate model value in the alert

I have the following piece of code: $(document).ready(function () { var edit= @Model.Edit.ToString().ToLower(); if( edit !=true ) { $("#editWriteup").hide(); } var date= @Model.EndDate; alert(date); ...

What is the best way to send an object key/value pair to a Vue template?

I've made progress on my component, but I'm facing an issue where the links are going to http://localhost:5173/[object%20Object]. It seems like I've reached a mental roadblock. This is what my component looks like: <template lang="p ...

Utilizing React to Style Background Positions

I've been struggling to position a block of rendered jsx on the right side of the first block for hours now. Despite trying various options like marginTop, marginLeft, and even backgroundPosition based on my research, I still haven't been success ...

Removing files from Dropzone.js uploaded form

For my project, I am utilizing dropzone.js and faced with the task of deleting files from the plugin upload zone (rather than the server) after they have been uploaded. My goal is to revert back to displaying the "Drop files here or click to upload" text o ...

Issue with ASP.NET Core Controller not properly receiving complete JavaScript array object from Ajax call

When passing a JavaScript Object Array through ajax to the controller, I noticed that if there are more than 11 objects in the array, the controller receives it as null. However, with 11 or fewer objects, the array is received successfully. Here is an exam ...

"Implementation of Google+ button causing the appearance of a horizontal scrollbar

Adding Facebook and Twitter sharing buttons was easy, but now I'm having trouble with Google+. No matter where I place the code on my page (using a Bootstrap grid), it always adds 2-3 pixels on the right side, creating a horizontal scrollbar: <div ...

The dynamic duo of web development: React and Bootstrap JavaScript

As I work with ReactJS, I have come to understand that using JQuery or vanilla JS to directly manipulate the DOM is not recommended. This is because ReactJS operates using a virtual DOM, which can lead to unpredictable outcomes. My question now is: if I w ...

Guide on making an NPM package with a web worker integration

Currently, I am in the process of developing an npm package that incorporates a web worker with type module. The issue arises when I try to link this package to a React application for testing purposes since the application cannot locate the worker.js file ...

Cross-origin resource sharing (CORS) policy issue arises when the 'Access-Control-Allow-Origin' header is not included in the requested resource, especially when utilizing an iframe in a React

I am trying to link a website to a button using an iframe. This website allows access to all domain names. Below is the code for my button: <Button component={NavLink} activeClassName={classes.activeBtn} to="/searchEngine&qu ...

Issue in TypeScript where object properties may still be considered undefined even after verifying using Object.values() for undefined values

I'm encountering an issue with TypeScript regarding my interface MentionItem. Both the id and value properties are supposed to be strings, but TypeScript is flagging them as possibly string | undefined. Interestingly, manually checking that id and va ...

Troubleshooting issue: Asynchronous functionality not working with Ajax.BeginForm

Struggling to grasp ASP.Net MVC and facing challenges with using Ajax.BeginForm to update a partial view asynchronously. Here's the code snippet in the view for the action: @using (Ajax.BeginForm( new AjaxOptions { ...

How to modify values in a JSON array using JavaScript

Currently, I am facing an issue with displaying dates properly on the x-axis of a graph created using Highcharts. To solve this problem, I need to parse the dates from the JSON response. Despite my attempts to manipulate the JSON date, I have not been able ...

AngularJS approach to binding window scroll

Hey there, I'm a newcomer to AngularJS with a background in jQuery. I'm trying to create a fixed-top navbar using AngularJS that has a background which changes from transparent to opaque as the window is scrolled. Unfortunately, I'm struggli ...

Utilizing Google Maps with WebGL to place multiple GLTF objects on a vector map based on geographical coordinates

Trying to incorporate 3D objects onto a Google Map overlay view using Three.js The main goal is to display bus stations using 3D objects with specific longitudes and latitudes Attempted to use the '@googlemaps/three' 'latLngAltitudeToVecto ...

Connecting with two instances of a socket.io client

Despite trying out the suggested options from the socketio website to adjust reconnection time, disable connection upgrade, and force new connections, I still end up with 2 connections each time the client page loads. Does anyone have any insights on what ...

How can Protractor find elements using non-HTML custom attributes?

When running e2e tests on my Angular project using Selenium WebDriver and Protractor, I encountered an issue with locating elements that have custom attributes. For example, I have an element like: <div my-directive my-unique-id="abc123"></div> ...

Dealing with an input containing HTML code within its value (manipulating with jQuery)

I developed a custom function that functions similarly to an edit-in-place plugin. Here is what it does: It retrieves the html content of an element when clicked: var editable = $(this).html(); It creates a text input field (or retrieves it if already ...

Is there a way for my command to respond only when a bot is mentioned?

Beginning of my command: I attempted to use if(member === bot) return message.channel.send("You can't rob bots") Unfortunately, it did not work as expected. Any assistance would be greatly appreciated. client.on('message', async message => ...