sungyong
sungyong

Reputation: 2499

Get all list from one firestore collection with VueJS

I want to display all user list by firestore query. But I stuck at promise chain. To query documents of collection, two asyncronous steps needed. How can I get wait until fill all list set.

Here is my code. I hope my fetchUsers() fill array without call back chain.

const db = firebase.firestore();

export default {
  data: () => {
    return {
      users: [],
    }
  },
  mounted: function() {
      this.fetchUsers()
      console.info('mounted, users:', this.users) // // => at this point, this.users is not yet ready.
  },
  computed: {
      items: function() {
          return this.users
      }
  },
  methods: {
    async fetchUsers () {
        await db.collection('users').get()
            .then(snapshot => {
                snapshot.forEach( doc => {
                    const user = doc.data()
                    console.log('forEarch:' , user)
                    user.id = doc.id
                    this.users.push(user)
                })
            })
            .catch(error => {
                console.error(error)
            })
        console.debug('fetchUser return: ', this.users)  // => at this point, this.users is not yet ready.
    },

Upvotes: 0

Views: 2705

Answers (1)

MichelDelpech
MichelDelpech

Reputation: 863

Don't mix async/await syntax with then/catch

const query = db.collection('users')

async fetchUsers () {
    try {
        const { docs } = await query.get()

        this.users = docs.map(doc => {
          const { id } = doc
          const data = doc.data()
          return { id, ...data }
        })

        console.log('Loaded users', this.users)
    } catch (error) { throw new Error('Something gone wrong!') }
}

Upvotes: 2

Related Questions