I currently have the following code.
dbSetOrderTemplate(tx) {
tx.executeSql('SELECT * FROM dr_template_relational WHERE template_id = (?)', [this.state.currentTemplateId],
(trans, result) => {
let currentOption;
const resultValue = result.rows._array;
let categories = [];
resultValue.forEach(function (item, index) {
if(currentOption != item.categories_id) {
// looping through results to get each item in sqlite db
tx.executeSql('SELECT * FROM dr_report_categories WHERE id = (?)', [item.categories_id],
(transCat, catResult) => {
categories.push(catResult.rows._array[0].name);
});
console.log(categories);
}
currentOption = item.categories_id;
});
},
(err) => console.error(err)
);
}
The above code runs and selects an array of items from a local sqlite database. So in the first 'SELECT * FROM dr_template_relational WHERE template_id = (?)'
I'm selecting an array and I pass to a const resultValue
. Then on resultValue I do a forEach to loop through each item and then my goal is to push it to variable categories.
categories isn't being pushed into, in the currently declared variable. Obviously a problem with Scope but I can't figure out why.
I declare: let categories = []
; then I run my foreach and then I execute another function called tx.executeSql. The tx.executeSql is a method inside of Expo for react native. I would expect categories.push to be pushing to the outside variable.
This works and gives me a console.log of the array pushed:
(transCat, catResult) => {
categories.push(catResult.rows._array[0].name);
console.log(categories);
}
but if I step out of tx.executeSql method:
tx.executeSql('SELECT * FROM dr_report_categories WHERE id = (?)', [item.categories_id],
(transCat, catResult) => {
categories.push(catResult.rows._array[0].name);
});
console.log(categories);
This shows console.log Array []
;
If categories isn't being read by the method then categories should cause an error undefined, no? I can't figure out what I'm doing wrong here. Please advice, thank you!