In my React-native app, I have a function that iterates through keys in an array and retrieves the corresponding reference from Firebase.
However, I am encountering an issue within the for loop where the key value is always 3. As a result, the variable totalItemsCompleted
(which represents the length of the key's value in userItemsArray
) is consistently set to 3.
listenForItems(itemsRef) {
var userItemsArray = {
0: [1],
1: [5, 6],
2: [8, 9, 10],
3: [11, 12, 13]
};
var pastItems = [];
var currentItems = [];
for (var key in userItemsArray) {
console.log("KEY1 " + key); //key value correct at this point
var itemRef = itemsRef.child(key);
itemRef.on('value', (snap) => {
var totalItemsOnList = snap.val().items.length;
var totalItemsCompleted = userItemsArray[key].length;
console.log("KEY2 " + key); //key value always 3 here
if (totalItemsOnList === totalItemsCompleted) {
pastItems.push({
title: snap.val().title,
});
}
else {
currentItems.push({
title: snap.val().title,
});
}
this.setState({
currentItems: this.state.currentItems.cloneWithRows(currentItems),
pastItems: this.state.pastItems.cloneWithRows(pastItems)
});
});
}
}