I've created a page where I want to get all my data from the database with an API call, but I'm kinda new to VueJS and Javascript aswell and I don't know where I'm getting it wrong. I did test it with Postman and I get the correct JSON back.
This is what I get:
[__ob__: Observer]
length: 0
__ob__: Observer {value: Array(0), dep: Dep, vmCount: 0}
__proto__: Array
This is what I want:
(140) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]
[0 … 99]
[100 … 139]
length: 140
__ob__: Observer {value: Array(140), dep: Dep, vmCount: 0}
__proto__: Array
Thats my Vue template file:
<template>
<div>
<h2>Pigeons in the racing loft</h2>
<div class="card-content m-b-20" v-for="pigeon in pigeons" v-bind:key="pigeon.id">
<h3>{{ pigeon.id }}</h3>
</div>
</div>
</template>
<script>
export default {
data(){
return{
pigeons: [],
pigeon: {
id: '',
sex: '',
color_id: '',
pattern_id: '',
user_id: '',
loft_id: '',
country: '',
experience: '',
form: '',
fatique: ''
},
pigeon_id: ''
}
},
created(){
this.fetchPigeons();
console.log(this.pigeons); // Here I got the observer data instead my array
},
methods: {
fetchPigeons(){
fetch('api/racingloft')
.then(res => res.json())
.then(res => {
console.log(res.data); // Here I get what I need
this.pigeons = res.data;
})
}
}
}
</script>
I've tried to do it with axios aswell, but it gave me exactly the same thing. When I console it from the method it gives my data, but outside it just gives nothing.
You can use
v-if
directive to render the component once the data is there.Can also try this:
It was brought by Evan You himself here and more info on that here
But waiting for the answer is a first step.
You should probably wait for the fetch to finish then console.log the result ..
The way you were doing it you were logging the result synchronously so it gets executed before the fetch is done.
Edit: Also as @barbsan pointed out in his comment below your
fetchPigeons
needs to return a promise forthen
to work.fetch
returns a promise so you just need to return fetch infetchPigeons
As mentioned by Husam Ibrahim, you should wait the async fetch() function to resolve. Another approach could be use async/await in your function:
And then it should work: