I try to get data from database by use 'getDoc' and .then(). After I get data I push it to the array. But when i acces data in then() i can access. But after i access in sam function, after get out from then(). i can't access. Sorry to bad naming.
const totalDBPromise2 = getDocs("Road");
let loaded2 = false;
let totalDB2 = [];
let totalNameDB2 = []
totalDBPromise2.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
if (!totalDB2.includes(doc.data())) {
totalDB2[doc.data().name] = doc.data()
}
loaded2 = true;
});
console.log(totalDB2['road1']) //I can access. I can get right result
});
console.log(totalDB2['road1']) // I can access. The result was undefined
I try to make it work. But i fail to solve.
CodePudding user response:
your second console runs before you'r first and before your promise resolved. ** totalDBPromise2** is a promise and it will take time to get values.
so use async/await or use useState which will reflect when changes made to state