Reputation: 117
New to React Native, and Javascript in general. Currently, I am trying to enact a Promise to handle an undefined error while using the react-native-sqlite-storage
package.
I was following this previous post here, but have not succeeded in implementing the Promise properly from what I can tell.
Here my current function:
nextPackage (q_id: number) {
return new Promise((resolve, reject) =>
db.transaction(tx => {
tx.executeSql(
'SELECT * FROM Questions INNER JOIN Choices on Choices.q_id = Questions.global_id WHERE Questions.global_id = ?', [q_id], (tx, results) => {
for (let i = 0; i < results.rows.length; i++) {
console.log('item:', i);
console.log('row:', results.rows.item(i));
this.pack.push(results.rows.item(i));
}
resolve(this.pack);
}, function (tx, error) {
reject(error);
});
})
)
}
And the Screen that calls it:
this.pack = this.wrapper.nextPackage(this.session.data_next.qID)
.then(data => {
console.log("Retrieved data: ", data);
})
.catch(error => {
console.error(error);
})
this.pkHelp = new PackageHelper(this.pack);
However, when I then try to access this.pack[0]
I receive an undefined is not an object (evaluating 'this.pack[0].choiceType')
. console.log() has shown that the database rows are indeed being read in, and that choiceType is indeed the proper column name.
Thanks in advance for any assistance!
Upvotes: 2
Views: 3781
Reputation: 11171
You can't assign the value to your pack like this. The returned value is in the then
part. You can do something like this
this.wrapper.nextPackage(this.session.data_next.qID).then(data => {
this.pkHelp = new PackageHelper(this.pack);
}).catch(error => {
console.error(error);
});
Or you can use await
. But you have to use it in the async
function
try {
this.pkHelp = await this.wrapper.nextPackage(this.session.data_next.qID);
this.pkHelp = new PackageHelper(this.pack);
} catch(error) {
console.error(error);
}
Upvotes: 2