Skip to content Skip to sidebar Skip to footer

Return Data To Component From Db Helper Class React Native

I am using sqlite and I have created a db helper class. I am not getting the data from that class inside component, but if I am consoling inside db helper it is working right, but

Solution 1:

Its an async operation, which means it is a promise. Best way would be to pass a callback to the function or return the db operation as promise and chain then. Some documentation on Promises in javascript is here.

With callback:

classCartDB {
constructor(){

}
totalItems = 0;
checkCountOfProduct(callback){
    query = "SELECT SUM(count) AS product_count FROM Predefinedcart";
   db.transaction((tx) => {
        tx.executeSql(query, [], (tx, results) => {
            console.log(results.rows.item(0).product_count)
            this.totalItems = results.rows.item(0).product_count;
            callback(this.totalItems)
        }, function (tx, error) {
            console.log('SELECT error: ' + error.message);
        });
    })
}
}

and in Comp you call: CartDB.checkCountOfProduct(count => console.log(count));

With promise:

classCartDB {
constructor(){

}
totalItems = 0;
checkCountOfProduct(){
    query = "SELECT SUM(count) AS product_count FROM Predefinedcart";
   returnnewPromise((resolve, reject) => db.transaction((tx) => {
        tx.executeSql(query, [], (tx, results) => {
            console.log(results.rows.item(0).product_count)
            this.totalItems = results.rows.item(0).product_count;
            resolve(this.totalItems);
        }, function (tx, error) {
            reject(error);
        });
    }))
}
}

and in Comp you call: CartDB.checkCountOfProduct().then(count => console.log(count));

Post a Comment for "Return Data To Component From Db Helper Class React Native"