Join the Stack Overflow Community
Stack Overflow is a community of 6.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

Im receiving array of objects from backend in below format. I am trying to get these datas and push it into a JavaScript array so that I can use them later on based on my needs.

[
    {
    id: 1,
    name: "Dr. Darrin Frami III",
    email: "[email protected]",
    address: "42568 Cameron Cove Fritschborough, MA 86432-0749",

    },
]

here is my vuejs code:

<script>
    export default {
      data(){
        return {
          fakeUsers: [],
          fakeUser: {id: '', name: '', email: ''},
        } 
      },
      methods:{

      },
        mounted() {
            var route = '/get-users';
            this.$http.get(route).then((response)=>{
              for (var i = 0; i < response.data.length; i++) {
                 this.fakeUser.id = response.data[i].id;
                 this.fakeUser.name = response.data[i].name;
                 this.fakeUser.email = response.data[i].email;
                 this.fakeUsers.push(this.fakeUser);
              }

            });
            console.log(this.fakeUsers);
            console.log(this.fakeUsers[0]);
        }
    }
</script>

the vue-dev tool result:

enter image description here

Output of the line console.log(this.fakeUsers); is [__ob__: Observer]. Shouldnt it print something like [Array[10]] ??

Output of the lineconsole.log(this.fakeUsers[0]); is undefinded I cant figure out why.. ? please help

share|improve this question
    
Nice email there... – George Kagan Nov 10 '16 at 12:04
    
generated using faker -_- – Noob Coder Nov 10 '16 at 12:06
up vote 4 down vote accepted

$http() creates an async ajax call, so the code in then() is executed after the console command after it.

Simple solution: put the console commands into the function in .then() as well.

share|improve this answer
    
excellent answer mate.. but i need to know one more thing.. as im new with vuejs.. and have not finished reading all documentations yet. just watched some tutorials. but i have one query, how can i get the first element after the ajax call is complete when the page loads? @linus – Noob Coder Nov 10 '16 at 14:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.