I was trying to write a class method to list out employee's name from google Firestore. The class is then use in other pages.
getDocs()
to get DocumentSnapShot of the collection, the documents are all push into an array.CustomFunction.ts
class Employee {
private UserCollection = collection(db, "User")
array: object[] = []
public async getEmployees() {
try {
const UserDocuments = await getDocs(this.UserCollection)
UserDocuments.forEach((docs) => {
this.array.push(docs.data())
})
}
catch (error) {
console.log(`Error message: ${error}`)
}
console.log(this.array)
}
}
export const EmployeeList = Employee
EmployeeList.vue
const Employees = new EmployeeList()
let FetchUser = async () => { await Employees.getEmployees() }
FetchUser()
console.log(Employees.array)
Log shows from EmployeeList.vue:
Log shows from CustomFunction.ts:
I tried indexing both arrays, array on EmployeeList.vue shows undefined while array on CustomFunctions.ts did give me the object I had indexed.
May I know why the array in EmployeeList.vue is empty?
As Tim commented, you'll need to await FetchUser()
. Without that, your console.log(Employees.array)
runs before the asynchronous call has completed.
If dealing with asynchronous calls in JavaScript is new for you, I recommend checking out the MDN documentation on Asynchronous JavaScript.