Matthias
Matthias

Reputation: 495

React Native - SQLite transaction is not waiting for result

I want to fetch data from a database (profile and config etc.) and wait for the data before calling the next functions. I was expectiong, that if I put the transaction in a function, call this function in an async function and wait, this would work, but it doesn't:

function getProfileData() {
    return db.transaction(
      tx => {
        tx.executeSql('SELECT value FROM tbl_config WHERE name="user_email"', [], (tx, results) => {
          console.log(results.rows.item(0).value);
          return results.rows.item(0).value;
      });
    }, null, null); 
}

async function fetchData() {
  console.log('before fetch')
  var res = await getProfileData();
  console.log(res);
  console.log('after fetch');
}

fetchData(); 

The console shows me the result from the function getProfileData(), but in the async function var res = await getProfileData() is undefined.

How do I fetch data step by step?

Upvotes: 1

Views: 2812

Answers (2)

Hend El-Sahli
Hend El-Sahli

Reputation: 6742

getProfileData function is not an async function ... and you can't do this:

await db.transaction(...);

The only way to fetch transaction result is through the callback, so you could do something like this:

tx => {
  tx.executeSql('SELECT value FROM tbl_config WHERE name="user_email"', [], (tx, results) => {
    console.log(results.rows.item(0).value);
    const result = results.rows.item(0).value;
    this.setState({ result  });
});

and then you could access state > result wherever you want in the code

Upvotes: 0

Nooruddin Lakhani
Nooruddin Lakhani

Reputation: 6967

Try this way

function callback(res){
  console.log(res);
  console.log('after fetch');
}

function getProfileData() {
    return db.transaction(
      tx => {
        tx.executeSql('SELECT value FROM tbl_config WHERE name="user_email"', [], (tx, results) => {
          console.log(results.rows.item(0).value);
          callback(results.rows.item(0).value); <!-- Change here -->
      });
    }, null, null); 
}

async function fetchData() {
  console.log('before fetch')
  await getProfileData();
}

Upvotes: 3

Related Questions