Chris
Chris

Reputation: 5073

Vue ajax request isn't updating data

I'm new to Vue but from my research this should be working. the console keeps showing users as null but when i look at the response of the request it has the users. I thought the => was supposed to update the vue instance.

...
data () {
  return {
    users: null,
  }
},
...
methods: {
  getUsers () {
    this.$axios.get('/api/users')
      .then(r => {
        this.users = r.data
      })
    console.log(this.users)
  },
},
...
created () {
  this.getUsers()
  this.users.forEach(function (u) {
    ...
  })
}

Upvotes: 0

Views: 85

Answers (2)

Sebastian Sulinski
Sebastian Sulinski

Reputation: 6055

If you want to loop through the collection of users, you have to first wait until they are actually available - you can use then callback for it:

export default {
  data () {
    return {
      users: [],
    }
  },
  methods: {
    getUsers () {
      return this.$axios.get('/api/users')
        .then(r => {
          this.users = r.data
        })
        .catch(error => console.log(error));
    },
  },
  created () {
    this.getUsers().then(() => {
      this.users.forEach(function (u) {
      ...
      })
    })
  }
}

Rather than converting returned collection from within vue component it would be better to return it formatted with the response - using plain php you could achieve it with array_map - here I'm using an array of User models as an example:

$users = array_map(function (User $user) {
    return [
        'value' => $user->id,
        'name' => $user->name,
    ];
}, $users);

The above will return something like:

[
    [
        'value' => 1,
        'name' => 'Jon Doe',
    ],
    [
        'value' => 2,
        'name' => 'Jane Doe',
    ],
]

Upvotes: 3

JakeParis
JakeParis

Reputation: 11210

You can move your users processing to a watcher:

...
data () {
  return {
    users:[],
  }
},
watch: {
  users (users) {
    if( ! this.users.length )
       return;
    this.users.forEach(function (u) {
      ...
    })
  },
},
...
methods: {
  getUsers () {
    this.$axios.get('/api/users')
      .then(r => {
        this.users = r.data
      })
    console.log(this.users)
  },
},
...
created () {
  this.getUsers()
}

Or if you prefer a one time processing, make it a method and call that method in the axios then():

...
methods: {
  getUsers () {
    this.$axios.get('/api/users')
      .then(r => {
        this.users = r.data
        this.processUsers();
      })
    console.log(this.users)
  },
  processUsers() {
     // do something with this.users
  },
},

Upvotes: -1

Related Questions