0

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 class="about">
    <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

1 Answer 1

1

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);
    }
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

It really works, thank you sir!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.