Rafaeatul
Rafaeatul

Reputation: 43

array in vue template is not updating

I am creating a dynamic array in my vue. This array is getting populated in script from a JSON array, but not updating in template. In template it is returning blank array. Here is my code:

<template>
  <div>
    {{users}} <!-- this is returning blank --> 
  </div>
</template>

<script>
  export default {
    data(){
      return {
        users: []
      }
    },
    created(){
      this.fetchUsers();
    },
    methods:{
      fetchUsers(){
        fetch('api/single')
          .then(res => res.json())
          .then(res => {
            this.users= res.data;
              console.log(this.users); //this is showing the data 
      })
        .catch(err => console.log(err));
   }
 }
};
</script>

Upvotes: 1

Views: 1791

Answers (4)

El Danielo
El Danielo

Reputation: 780

This happens when the data property value is not initialised in the correct way. Instead of assigning your array from the fetch request to your data property you should use vm.$set method provided by Vue api. Thanks to this reactivity will be preserved. In the matter of fact you can even remove the users array declaration from your data object since vm.$set will override it.

So your method will look like this:

fetchUsers(){
        fetch('api/single')
        .then(res => res.json())
        .then(res => {
            this.$set(this, 'users', res.data) // target, key, value
        })
        .catch(err => console.log(err));
    }

Upvotes: 1

余俊浩
余俊浩

Reputation: 26

this.$nextTick( () => {
  this.fetchUsers();
})

You can try this.$nextTick(). Because, the update of the DOM is asynchronous in Vue.

Upvotes: 0

aarcoraci
aarcoraci

Reputation: 231

I believe the problem has to do with reactivity with arrays. Try using a foreach loop to populate your data or as suggested use vm.$set

res.data.forEach(element => {
  this.users.push(element);
});

For more information about arrays reactivity please take a look at vuejs common gotchas

Upvotes: 0

Adrien Rosi
Adrien Rosi

Reputation: 132

Fetch API send asynchronous request, so users is displayed before data are loaded from API. Call computed method binded to users.

Upvotes: 0

Related Questions