Vue.js: Utilizing async/await in Vue.js results in an observer being returned

Currently, I'm attempting to retrieve data from an API and store it in an array. The issue arises when I try to log the response data from the API - the data is displayed just fine. I assign the value of a variable to the data obtained from awaiting the API call. However, when I use console.log on the variable, it shows that the value is an observer. I have tried using async/await and have installed:

"babel-plugin-transform-regenerator": "^6.26.0",
"babel-polyfill": "^6.26.0"

const baseUrl = "http://...";
    export default {
      name: "report",
      data() {
        return {
          selected: "",
          categories: []
        };
      },
      created() {},
      methods: {
        async getCategories() {
          this.categories = await axios
            .get(`${baseUrl}/feedback/search`)
            .then(res => {
              return res.data;
            });
        }
      },
      mounted() {
        this.getCategories(); // removed and tried adding this line again
        console.log("cat ", this.categories);
      }
    };

This is what I receive: cat -> [__ob__: Observer]. This approach also does not seem to work for me. What am I missing here?

I've been grappling with this issue for hours, trying various solutions found on Stack Overflow without success (or perhaps I'm overlooking something). Being new to Vue.js, I would greatly appreciate some guidance!

Answer №1

Make sure to wait for this.getCategories() to finish before logging this.categories. If you log it before the method resolves, this.categories will still be empty due to how Vue handles reactivity with the __ob__ property.

To fix this issue, use await in the mounted hook:

async mounted() {
  await this.getCategories();
  console.log("cat ", this.categories);
}

Check out the demo here

Answer №2

Can you please give this a shot?

const mainUrl = "http://...";
export default {
  name: "report",
  data() {
    return {
      selected: "",
      categories: []
    };
  },
  created() {},
  methods: {
    async fetchImageCategories() {
      this.categories = await axios
        .get(`${mainUrl}/feedback/search`)
        .then(res => {
          return res.data;
        });
    }
  },
  async mounted() {
  await this.fetchCategories(); // removed and tried adding this line again
    console.log("categories ", this.categories);
  }
};

Answer №3

One easy way to debug is by logging the received data

async fetchCategories() {
   const response = await axios.get(`${baseUrl}/feedback/search`)
   const fetchedData = await response.data
   console.log('categories: ', fetchedData)
   this.categoriesList = fetchedData
}

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

Enhance your SVG progress circle by simply selecting checkboxes

I have a unique system with 5 checkboxes that act as a To-Do list. When I click on each checkbox, the circle's diameter should progressively fill up in increments of 1/5 until all 5 checkboxes are completed. The order in which the checkboxes are click ...

The action 'onDeleteClick' cannot be executed as the property is undefined

Why is the onDeleteClick function working on the first <div>, but returning undefined on the second one? I am able to access the reference of this, but when clicking, it shows "onDeleteClick of undefined". I am confused as to why the onDeleteClick f ...

Carousel-Owl, glide through two items simultaneously

I am currently in the process of developing a slider using the beta version of Owl-Carousel 2, but I am encountering several issues. My goal is to configure the owlCarousel to function as follows: It should scroll through 2 items at a time while displayin ...

Glass-pane or angular/HTML overlay on a designated element

Is there a way to create a glass-pane effect, like an hourglass symbol on a semi-transparent layer, within the boundaries of an HTML element E? The goal is to have the glass-pane only overlap the area within E's boundaries. When the glass-pane is ac ...

What is the best way to extract information from a JavaScript page when the content is identified by a reference?

If you're looking for the website, you can visit . It's primarily in Chinese, but that may not be relevant to the topic at hand. Currently, I am able to extract all the content from this page and now I'm interested in moving on to the next ...

What is the internal mechanism behind the operation of JavaScript function parameters?

As someone who is new to programming, I've been struggling to understand how parameters and arguments work behind the scenes. For example: function changeStuff(a) { return a = a * 10; } var num = 10; console.log(changeStuff(num)); / ...

How to display and retrieve data from a JSON object using JavaScript

Having trouble retrieving input values from a JSON object and getting 'undefined' when running the code. Any suggestions or ideas would be greatly appreciated as I have tried various approaches. Additionally, I need to utilize JSON for my school ...

Transforming JSON output into a string without any prior understanding

My AJAX function generates a JSON output which also includes unnecessary XML due to an error in the JSON WebService. To remove this XML, I have utilized JavaScript Regular Expressions. AJAX Function function setJsonSer() { var strWsUrl = 'https: ...

Creating TypeScript models from a JSON response in React components

My Angular 2 application retrieves a JSON string, and I am looking to map its values to a model. According to my understanding, a TypeScript model file is used to assist in mapping an HTTP Get response to an object - in this case, a class named 'Custo ...

Deciphering the Results of AngularJS

What sets 'template' apart from 'templateUrl' in AngularJS directive? index.html: <!DOCTYPE html> <html lang="en" ng-app="app"> <head> <meta charset="utf-8"> <title>Index</title> </he ...

Discovering the process of previewing a video upload using react-player

Currently, I have an input that allows users to upload video files of type File. In my application, there is also a react-player component that requires a URL prop, which can be either an array or MediaStream according to its documentation. After doing som ...

Switch between selecting every group of 3 items and every group of 4 items

Having an array with more than 14 items, I need to group them into 2 different groups in this specific way: The first 3 (#1,2,3) will be in array A, the next 4 (#4,5,6,7) will be in array B, the following 3 (#8,9,10) will be in array A, the subsequent 4 (# ...

I am looking for assistance constructing a task management application using vue.js

I am facing an issue with developing a to-do list using Vue.js. The goal is to add tasks to the list by entering them and clicking a button. Once added, the new task should show up under "All Tasks" and "Not finished". Buttons for marking tasks as " ...

Using Vue.js to bind labels and radio buttons in a form

My goal is to generate a dynamic list of form polls based on the data. However, using :for or v-bind:for does not result in any HTML markup appearing in the browser, causing the labels to not select the corresponding input when clicked. I have prepared a J ...

The scroll feature in JavaScript is malfunctioning

After countless hours of troubleshooting, I still can't figure out why the code snippet below is not working properly on my website at : <script> $(window).scroll(function () { if ($(window).scrollTop() > 400) { ...

Having trouble installing gatsby-plugin-transition-link using npm

https://i.stack.imgur.com/DyZxQ.png I'm facing some issues while trying to install gatsby-plugin-transition-link using npm. No matter what solutions I've attempted, the errors persist. Can anyone provide insight into what might be causing this p ...

display object issue with object display

I'm encountering a strange issue with my constructor objects in JS - when I try to view them, all I see is [object Object]. Can anyone help me figure out why this is happening? Check out the code snippet on MyCodeFiddle. ...

I'm experiencing unexpected behavior with the <form> element in React, it's not functioning as I

I have encountered a strange behavior while trying to implement a form element for user input. When I directly insert the form element, everything works perfectly fine as I type in the letters. However, if I insert the form element through the AddForm comp ...

"Encountering a KnexTimeoutError while utilizing the knex.transactionProvider() function

I am currently working on implementing Knex transactions into my project using the relevant files provided below. However, I am encountering the following error: KnexTimeoutError: Knex: Timeout acquiring a connection. The pool is probably full. Are you ...

"Master the art of using express and jade to loop through data and generate dynamic

Hey there! I have a question regarding node.js. When working with express, we typically have multiple files such as app.js, index.jade, index.js, and server.js where most of the server logic resides. Let's say we have two objects defined in server.js ...