0

I'm messing around with a few vue chat libraries and I have this code:

<template>
    <p>{{ this.users[0] }}</p>
</template>


<script>
export default {

  data() {
    return {
      users: []
    }
  },
  mounted() {
    firestoreService.getAllUsers().then(({ data }) => {
      data.forEach((user, i) => {
        this.users[i] = user
      });
    })
  }
</script>

Basically I have a firestore index where I store my users and on mount hook I populate the users array but for some reason vue does not see the data. Any ideas?

If I console.log the data I can see the data in the console.

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87

1 Answers1

0

The assignments of array elements by index are not reactive in Vue 2. The reactivity can be triggered by the use of Vue.set, or array methods like push, e.g.:

  data.forEach((user, i) => {
    Vue.set(this.users, i, user);
  });

Since an array needs to be fully replaced, a correct way is to replace the whole array with the result, as it has been already suggested in comments:

firestoreService.getAllUsers().then(({ data }) => {
  this.users = data
})
Estus Flask
  • 206,104
  • 70
  • 425
  • 565