I have this code in my react native app that is using firebase :
let bestTutors = [];
const getBestTutors = async () => {
const snapshot = await getDoc(docRef);
bestTutors = snapshot.data().list;
}
getBestTutors();
console.log(bestTutors);
But when i run it it only console logs "Array[ ]", I've tried to using .then( ) and all kind other stuff that doesn't make sense for me, idk if there's a wey to use it without the await or How can i pass the data to the variable :( ?
call function with await. Like this one
await getBestTutors()
Look at my comments
Your Code 1
let bestTutors = [];
const getBestTutors = async () => {
const snapshot = await getDoc(docRef);
bestTutors = snapshot.data().list;
}
getBestTutors(); // Asynchronous function
console.log(bestTutors); // this is called before getBestTutors() returns the data. So console.log(bestTutors) return de default value: []
The new code
let bestTutors = [];
const getBestTutors = async () => {
const snapshot = await getDoc(docRef);
bestTutors = snapshot.data().list;
}
await getBestTutors(); // Wait until getBestTutors() has finished and then Next.
console.log(bestTutors);