Home > Net >  Failed returning data from array
Failed returning data from array

Time:04-19

i have a problem which that i cannot see the data inside array that i have pushed the data inside .then from axios

Here are the sample code Axios from vue.js

export default {
  name: 'facts',
  data(){
    const test = [{id: 'test',name: 'test'}]
    const response = [];
    const factsData = () => {
      axios.get('http://localhost:3000').then(x=>response.push(x.data))
    }
    factsData();
    console.log(response)
    return{
      test,
      response
    };
  }
};

When i tried to console.log the output data inside the promise(.then) it worked well and display the data that i expected like this previous code

expected output data

and this is what happen when i tried to push the data from axios to response and show the output data in console.log with my current code above

enter image description here

when i tried to access it (console.log(response[0]), it shows undefined in console.log.

enter image description here

But strangely, when i back to my previous code to not to tried to access the data and i expand the array in console browser, it shows data that i expected which mean i couldn't access it.

enter image description here

The main purpose is i want to dipsplay the data to be rendered in table using v-for

<template>
  <div >
    <center>
      <table>
        <thead>
          <tr>
            <th></th>
            <th>ID</th>
            <th>Username</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(user,index) in test" :key="user.id">
            <td>{{index   1}}</td>
            <td>{{user.id}}</td>
            <td>{{user.name}}</td>
          </tr>
        </tbody>
      </table>
    </center>
  </div>
</template>

Please tell me what i'm missing. Thank you.

P.S : I'm new to this vue js

CodePudding user response:

your code structure is not correct. use this code:

export default {
  name: 'ProfilePage',

  data() {
    return {
      response: []
    }
  },

  created () {
    this.getData();
  },

  methods: {
    getData() {
      axios.get('http://localhost:3000').then(x => this.response = x.data);
    }
  }
}
  • Related