2

I'm trying to return the results of the query but I always get undefined. I'm not sure what I'm doing wrong here. I'm using react native with sqlite storage plugin.

let SQLite = require('react-native-sqlite-storage')
let db = SQLite.openDatabase({name : "db.v1.33", createFromLocation : "~db.db"});
let sqlResults;

export function GetQuestions(sqlType,questionsCount) {
    let sqlQuestions = `SELECT * FROM Questions WHERE Type IN (${sqlType}) ORDER BY RANDOM() LIMIT ${questionsCount}`

    db.transaction((tx) => {
        tx.executeSql(sqlQuestions, [], (tx, results) => {
            sqlSize = results.rows.length;
            sqlResults = results;
        });
    });

    return sqlResults;
}
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Taha
  • 551
  • 1
  • 5
  • 18

1 Answers1

1

The problem with this is that db.transaction is asynchronous, which means that it takes some time to do while the rest of the code moves on. So, db.transaction is started and then it immediately returns the sqlResults variable, which has not yet been set. What you need to do is return either a promise (quick tutorial here: https://developers.google.com/web/fundamentals/primers/promises) or set make your modifications in the callback (of tx.executeSql). Only then is the result set and usable.

iHowell
  • 2,263
  • 1
  • 25
  • 49