Search code examples
javascriptgoogle-cloud-firestore

obtaining objects from array but array shows empty


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.

  • After using getDocs() to get DocumentSnapShot of the collection, the documents are all push into an array.
  • The array is then called from the other web page
  • The array shows empty, but after expanding the array there is objects inside

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:

enter image description here

Log shows from CustomFunction.ts: enter image description here

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?


Solution

  • 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.