[Vuejs]-Save API data into an array with vue.js

1👍

From the code above I’m assuming the data in this.info in correct. The problems I see in your code are:

1.

.then(response => (this.info = response.data))
.then(() => info.data.forEach(element => {

}))

info looks to be undefined. I assume this should be this.info.

.then(response => (this.info = response.data))
.then(() => this.info.data.forEach(element => {

}))

Or if you’re using the arrow function syntax and returning an assignment expression, you can use

.then(response => (this.info = response.data))
.then(info => info.data.forEach(element => {

}))

Which I don’t really recommend, since some linting rules disallow returning assignment expressions (for good reasons). To chain a promise that relies on this implicit language behavior can make code less easily understood.

2.

What forEach does matters. Vue’s reactivity does not pick up certain assignment syntax, i.e. this.name[i] = element. You can use array methods like push, but I recommend you use functional programming operators, like map and filter:

.then(() => (this.name = this.info.data.map(element => {

})))

0👍

Maybe the this reference is not correct, because on callback methods is on another context, try it:

export default {
  data () {
    return {
      info: null,
      name: []
    }
  },
  mounted () {
    var self = this
    axios
      .get('http://localhost:3000/api/users/', {mode: 'no-cors'})
      .then(response => (self.info = response.data))
      .then(info.data.forEach(element => {

      });)
      .catch(error => {
        console.log(error)
        this.errored = true
      })
      .finally(this.loading = false)

  }
}

0👍

you forgot to encapsulate the callback into a function receiving the info variable,
try this:

import axios from 'axios'

export default {
  data () {
    return {
      info: null,
      name: []
    }
  },
  mounted () {
    axios
      .get('http://localhost:3000/api/users/', {mode: 'no-cors'})
      .then((response) => response.data.forEach(element => {

      }))
      .catch(error => {
        console.log(error)
        this.errored = true
      })
      .finally(this.loading = false)

  }
}

Leave a comment