Vue JS returns [__ob__: Observer] data instead of my array of objects

JavascriptArraysLaravelvue.jsAxios

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

Can also try this:

var parsedobj = JSON.parse(JSON.stringify(obj))
console.log(parsedobj)

It was brought by Evan You himself here and more info on that here

But waiting for the answer is a first step.

Solution 2 - Javascript

This happens because Vue js convert every item in the data to something that can be observed. So it makes sense if you console log something in the data. The output will be something wrapped into an observer.

To have a better vision on your data I suggest you to install the Vue dev tools. https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd?hl=en

Solution 3 - Javascript

Here is my solution:

add new method something like log to your $root component. App.vue's created is recommended:

this.$root.log = function log() {
  for (let i = 0; i < arguments.length; i += 1) {
    if (typeof (arguments[i]) === 'object') {
      try {
        arguments[i] = JSON.parse(JSON.stringify(arguments[i]));
      } catch (e) {
        console.error(e);
      }
    }
  }
  console.log(...arguments);
};

just call this.$root.log(this.pigeons) in your component.

My result:

BEFORE:

enter image description here

AFTER:

enter image description here

Solution 4 - Javascript

You should probably wait for the fetch to finish then console.log the result ..

created(){
    this.fetchPigeons().then(() => console.log(this.pigeons));
},

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 for then to work. fetch returns a promise so you just need to return fetch in fetchPigeons

fetchPigeons(){
    return fetch('api/racingloft')
    .then(res => res.json())
    .then(res => {
        console.log(res.data); // Here I get what I need
        this.pigeons = res.data;
    })
}

Solution 5 - Javascript

The best way possible

obj2 = JSON.stringify(obj)
obj3 = JSON.parse(obj2)

Or

obj2 = Object.assign([], obj)

It was brought by Evan You himself here and more info

Solution 6 - Javascript

Basically, what you've done is that the function fetches the pigeon array, but as its running in parallel, you called the console.log. Easy fix:

this.fetchPigeons().then(()=>{
  console.log(this.pigeons);
}

Solution 7 - Javascript

You can use v-if directive to render the component once the data is there.

<h3 v-if="pigeons.length > 0">{{ pigeon.id }}</h3>

Solution 8 - Javascript

As mentioned by Husam Ibrahim, you should wait the async fetch() function to resolve. Another approach could be use async/await in your function:

methods: {
    async fetchPigeons(){
        await fetch('api/racingloft')
               .then(res => res.json())
               .then(res => {
                   console.log(res.data);
                   this.pigeons = res.data;
               })
    }
}

And then it should work:

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

Solution 9 - Javascript

Thank you for all your suggestion. Things worked on my end by just using "const".

const cookieInfo = ToolCookieService.getToolNumbersFromCookie();

Thanks, Ranjit

Solution 10 - Javascript

I got the same problem still stuck ...

Wrote these according to Evan(Vue Author) JSON.parse(JSON.stringify(res.data)) method, But why can't normal data?

  methods: {
    async getdata() {
      console.log(1);
      await axios.get(API).then((res) => {
          console.log(2);
          if (!this.dataList.length) {
            this.dataList = JSON.parse(JSON.stringify(res.data));
            console.log(3);
            console.log(res.data, 'res.data ');
            console.log(this.dataList, 'this.dataList')
            console.log('----------check-----------',JSON.parse(JSON.stringify(res.data)));
          }
        })
        .catch(err => {
          console.error('failed: ' + err);
        })
      console.log(4);
    },

Solution 11 - Javascript

If your goal is debugging WHAT included in Observer Vue instance, this is my solution:

> Print out that variable in template block belongs to your Component

After that, you can reformat the structure of the output to observe the detail.

For example:

<template>
  <div>
    {{ pigeons }}
  <div>
</template>

Another way, if you wanna see it in console, you should put the console.log into mounted phase. Because at created phase, the this.pigeons still be empty. Ref: https://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram

Hope this helpful.

Solution 12 - Javascript

If you're returning an object instead an array and it has defined key props:

data () {
  return {
    object: {
      definedKey: [],
      anotherDefinedKey: []
    }
  }
}

Try check if the keys returned by your fetch are the same defined in your object, if you don't fulfill your object defined keys Vue will assume that you're still waiting for them.

Solution 13 - Javascript

Well I had exactly same problem but I solved it:

Just move app.js external link to head tag.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionshawnestView Question on Stackoverflow
Solution 1 - JavascriptguillimView Answer on Stackoverflow
Solution 2 - JavascriptKevin LE GOFFView Answer on Stackoverflow
Solution 3 - JavascriptmudinView Answer on Stackoverflow
Solution 4 - JavascriptHusam IbrahimView Answer on Stackoverflow
Solution 5 - Javascriptdev zarghamiView Answer on Stackoverflow
Solution 6 - JavascriptLucien950View Answer on Stackoverflow
Solution 7 - JavascriptYahyaView Answer on Stackoverflow
Solution 8 - JavascriptAndre RavazziView Answer on Stackoverflow
Solution 9 - Javascriptranjit0829View Answer on Stackoverflow
Solution 10 - JavascriptPeter PanView Answer on Stackoverflow
Solution 11 - JavascriptMatiandaView Answer on Stackoverflow
Solution 12 - JavascriptHenriqueyunView Answer on Stackoverflow
Solution 13 - JavascriptMorteza MohiuodinView Answer on Stackoverflow