0

I'm attempting to return a variable in ES6 with data loaded into it by a SQLLite transaction in Expo, but am unsure how to do this as it is always returning null.

import {SQLite} from 'expo';
import React from 'react';
const db = SQLite.openDatabase('db.db');
class CoreApp extends React.Component{

getLoginTokens = () => {
    var result = [];
    db.transaction(success, tx => {
        tx.executeSql(
            `SELECT token FROM tokens LIMIT 1;`,
            [],
            (_, { rows: { _array } }) => {
                result = _array;
            }
        );
    });
};
}

class SelectTour extends React.Component {
    render() {
        //
        CoreApp.getLoginTokens();
    }
}

When getLoginTokens is run, i would like to return the result, but everytime I console.log the result it is undefined.

If, i'm inside the scope of the tx.executeSql and I run console.log(_array) it shows a full array.

In ES6, How can I set the result properly? I'm currently using result = _array; but the result is not being set outside of the transaction.

Oliver Kucharzewski
  • 2,523
  • 4
  • 27
  • 51

1 Answers1

2

Using Promises:

getLoginTokens = () => new Promise((resolve, reject) => {
    db.transaction(success, tx => {
        tx.executeSql(
            `SELECT token FROM tokens LIMIT 1;`,
            [],
            (_, { rows: { _array } }) => {
                resolve(_array);
            }
        );
    });
});

now getLoginTokens returns a Promise which you can use in the regular way

getLoginTokens.then(results => console.log(results));

Old school callback

getLoginTokens = cb => {
    db.transaction(success, tx => {
        tx.executeSql(
            `SELECT token FROM tokens LIMIT 1;`,
            [],
            (_, { rows: { _array } }) => {
                cb(_array);
            }
        );
    });
};

usage

getLoginTokens(results => console.log(results));
Bravo
  • 6,022
  • 1
  • 10
  • 15