Shariq
Shariq

Reputation: 83

react-native-sqllite value not displayed

this.getDetails();

getDetails = () => {
     let userDetails = [];
     db.transaction((tx) => {
          tx.executeSql('select * from users where role=?',['students'],(tx,results) => {
               let details = []
               if(results.rows.length > 0){
                    for(let i=0; i < results.rows.length; i++){
                          details.push(results.rows.item(i));
                    }
               }
               userDetails = details;
               //Data is displayed  here
               console.log(userDetails)
          })
     })
     // Data is not printed here
     console.log(userDetails) // []
}

In the above code snippet , I am able to get the data(userDetails) inside the tx.executeSql but not outside the db.transaction block.

Can anyone please help me out how to display the data outside of the db.transaction block.

Upvotes: 0

Views: 68

Answers (1)

Honey
Honey

Reputation: 2398

Define a promise function for getting userDetails from DB.

async dbAction = () => {
  return new Promise((resolve, reject) => {
    db.transaction((tx) => {
          tx.executeSql('select * from users where role=?',['students'],(tx,results) => {
               let details = []
               if(results.rows.length > 0){
                    for(let i=0; i < results.rows.length; i++){
                          details.push(results.rows.item(i));
                    }
               }
               //Data is displayed  here
               resolve(details);
          })
     })
  });
}

And then you can call it like this.

getDetails = () => {
     let userDetails = [];
     try {
       let userDetails = await dbAction();
       console.log(userDetails);
     } catch (e) {
     }
}

Upvotes: 1

Related Questions