Whenever I use Vue JS, instead of receiving my array of objects, I am returned with [__ob__: Observer

Struggling to retrieve data from the database using an API call in my VueJS application. I'm new to VueJS and JavaScript, tested the API with Postman and received the correct JSON response.

Current output:

[__ob__: Observer]
length: 0
__ob__: Observer {value: Array(0), dep: Dep, vmCount: 0}
__proto__: Array

Expected output:

(140) [{…}, {…}, {…}, ...]
[0 … 99]
[100 … 139]
length: 140
__ob__: Observer {value: Array(140), dep: Dep, vmCount: 0}
__proto__: Array

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); // Getting observer data instead of the array here
    },

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

Tried using axios as well, but facing the same issue. Data is accessible within the method but not outside it.

Answer №1

Another option to consider:

var clonedObj = JSON.parse(JSON.stringify(originalObj))
console.log(clonedObj)

This valuable tip was shared by Evan You himself on this thread, and you can find more details here.

Remember, seeking out answers is just the first step.

Answer №3

Below is the solution I came up with:

To enhance your $root component, consider adding a new method named log. It is recommended to incorporate this within the created hook of your App.vue:

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);
};

To utilize this new method, simply call this.$root.log(this.pigeons) in your component.

Outcome achieved:

BEFORE:

https://i.sstatic.net/waNUK.png

AFTER:

https://i.sstatic.net/uYFOu.png

Answer №4

It's best to wait for the fetch operation to complete before logging the result.

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

If you log the result synchronously, it will happen before the fetch is finished.

Note: @barbsan mentioned in a comment that your fetchPigeons function should return a promise for the then method to work properly. Since fetch already returns a promise, simply return fetch in your fetchPigeons function.

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;
    })
}

Answer №5

The most effective method

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

Alternatively

obj2 = Object.assign([], obj)

This was introduced by none other than Evan You himself here with additional details

Answer №6

To display the component only when there is data available, utilize the v-if directive.

<h3 v-if="birds.length > 0">{{ bird.id }}</h3>

Answer №7

Husam Ibrahim emphasized the importance of allowing the async fetch() function to resolve before proceeding. Alternatively, you can implement async/await in your method:

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

By using this approach, your code should function as expected:

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

Answer №8

I appreciate the helpful suggestions. I was able to resolve my issue by simply utilizing the "const" keyword.

const cookieInfo = ToolCookieService.getToolNumbersFromCookie();

Best regards, Ranjit

Answer №9

Essentially, in this scenario, the function is retrieving the pigeon array, but since it's running concurrently, you invoked the console.log prematurely. The resolution is quite simple:

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

Answer №10

I'm facing the same issue and I'm still unable to find a solution...

Even after following Evan's (Vue Author) advice to use the JSON.parse(JSON.stringify(res.data)) method, I can't seem to retrieve normal data. What could be causing this?

  methods: {
    async fetchData() {
      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);
    },

Answer №11

When returning an object instead of an array with defined key props:

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

Make sure to verify if the keys returned by your fetch match those defined in your object. If they do not coincide, Vue will assume that you are still expecting them.

Answer №12

If you're looking to debug what's included in the Vue instance of `Observer`, here's a solution to consider:

Output the variable within the `template` block that belongs to your Component

Afterward, you can adjust the output's structure to observe the details.

For instance:

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

Another approach would be to use `console.log` within the `mounted` phase if you prefer viewing it in the console. This is because during the `created` phase, `this.pigeons` will still be empty. Reference: https://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram

I hope this proves helpful!

Answer №13

Wow, what an interesting dilemma! I too have encountered a similar issue, which seems to stem from the asynchronous returns creating two different object IDs.

I wonder if splitting the functionality into two separate functions could potentially resolve this instead of trying to handle it all within one function?

created(){
    this.fetchPigeons();
    console.log(this.pigeons); // It's strange how I'm getting observer data here rather than my expected array
},

methods: {
    async fetchPigeons(){
        await fetch('api/racingloft')
        .then(res => res.json())
        .then(res => {
            this.loadPigeonsData(res.data)
        })
    },
    loadPigeonsData(_data){
      console.log(_data); // Ah, finally seeing the data that I actually need
      this.pigeons = _data;
    }


}

Answer №14

Utilizing destructuring on the information is effective:

console.log({...object})

Answer №15

I encountered a similar issue, but I was able to find the solution:

Simply relocate the external link for app.js to the head tag.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to verify an NPM package for non-JavaScript code

How can we determine if an npm package consists purely of JavaScript without any bindings or dependencies that require compiling? For instance, the node-speaker package (https://github.com/TooTallNate/node-speaker) requires compilation (mpg321), while req ...

What kind of type is recommended to use when working with async dispatch in coding?

For my TypeScript and React project, I am currently working on an action file called loginAction.tsx. In this file, there is a specific line of code that handles the login functionality: export const login = (obj) => async dispatch => { dispatch( ...

Strange behavior of shadows within Three.js

I've been working on creating a mini solar system but encountered an interesting issue. I want all the planets to cast and receive shadows from each other, but it seems like the shadow casting depends on the order of instancing. Here is the code for t ...

Unable to submit with the enter key using vue-btn

I am have a common login form with a submit button at the end, currently requiring me to click the button with my mouse to submit. However, I would like to be able to simply press the enter key to submit the form. Here is the code for my button: <v-bt ...

Leverage the power of openCv.js within your next.js projects

I am attempting to incorporate openCv.js into my next.js application a. I started the project with: npx create-next-app b. Next, I installed: $ yarn add @techstark/opencv-js c. Imported OpenCV with: import cv from "@techstark/opencv-js" d. Ho ...

Custom dropdown feature in Vue-tables2

Is there a way to customize the select dropdown style in vue-tables2 table? I am trying to change the entire template of the dropdown, not just add CSS classes. My custom template includes additional elements like span and div tags that need to be incorpor ...

Is there a more efficient method for configuring mongo?

I'm dealing with a set of documents that are identical but can be categorized into two distinct groups based on their usage patterns. One group, referred to as "current", consists of a small number of documents that are queried frequently. The other ...

Change a vector into a three-dimensional matrix

I need to convert the vector shown below into a 3-dimensional matrix: v <- c(111,112,121,122,211,212,221,222) The desired outcome should look like this: ,,1 111 112 121 122 ,,2 211 212 221 222 When using the command dim(v) <- c(2,2,2), the result ...

What is the best way to implement this (click) function in Angular?

My goal is to create a set of three buttons with a (click) function attached to each. Initially, when the page loads, the first button should be selected while the other two are unselected. If I click on an already selected button, it should remain selecte ...

Toggle the visibility of an element with a single button click

Below is a snippet of my sample code: SAMPLE HTML CODE: <ul> <li class="item"> item 1 </li> <li class="item"> item 1 </li> <li class="item"> item 1 </li> <li class="item"> item 1 </li> <l ...

What is the best way to categorize a collection of objects within a string based on their distinct properties?

I am working with an array of hundreds of objects in JavaScript, each object follows this structure : object1 = { objectClass : Car, parentClass : Vehicle, name : BMW } object2 = { objectClass : Bicycle, parentClass : Vehicle, name : Giant } object3 = { ob ...

Struggling with TypeScript compilation in a Vue.js project? Encounter error code TS2352

Here is my code snippet from window.ts import Vue from 'vue' interface BrowserWindow extends Window { app: Vue } const browserWindow = window as BrowserWindow export default browserWindow Encountering a compilation error Error message: TS2 ...

Assigning nested JSON values using Jquery

My JSON data structure is as follows: { "Market": 0, "Marketer": null, "Notes": null, "SalesChannel": null, "ServiceLocations": [ { "ExtensionData": null, "AdminFee": 0, "CommodityType": 0, ...

Encountering difficulties when trying to send requests to an API through AJAX

Our company relies on the software nocrm.io for managing leads and customers. I am looking to integrate their API into our web application to streamline information exchange through GET and POST requests. However, I am facing challenges while trying to mak ...

Using an array as an integer in C

In my C code, I've written the following: int main(){ int a = {1, 2, 3}; } I've noticed that the variable 'a' seems to only take on the value of the first element in the array. This made me curious if the other elements are being d ...

Exploring the mocking of document,hidden using Jasmine

Struggling to simulate document.hidden in an angular unit test, but facing issues. Tried the following solutions: spyOn(Document.prototype, <any>'hidden').and.returnValue(true); spyOn(Document, <any>'hidden').and.ret ...

Hold off on showing the image until it has finished loading

// Here's the code snippet angular .module('imgapp', []) .controller('mainCtrl', mainCtrl); function mainCtrl() { var vm = this; vm.first = { title: 'Image 1', url: 'http://www.image-mapper.com ...

Creating a tab component using vanilla javascript

I am facing an issue with my tab component in plain JavaScript. The content displays correctly in debug mode, but after compilation, it does not show up on the browser. Additionally, when I select a tab, the 'activeNav' class is applied to indica ...

Retrieving information from Mongodb using Angularjs

Although my background is in a LAMP stack, my interest has recently been piqued by the Node.js/Angluarjs combo. I now want to incorporate Mongodb into the mix, but I'm struggling to set it up. Every tutorial I come across seems to use a different stac ...

Is there a way to dynamically hide specific ID elements in Javascript based on the size of the browser window?

I have spent countless hours searching for a solution to this issue without any success. The problem I am facing involves making certain elements on a webpage invisible when the browser window width is less than a specified size. The issue arises due to f ...