1

I'm receiving array of objects from backend in below format. I am trying to get this data 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]. Shouldn't it print something like [Array[10]]?

Output of the line console.log(this.fakeUsers[0]); is undefined, and I can't figure out why.

0

1 Answer 1

5

$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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

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.