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

Step-by-step guide for serving static JavaScript files using NextJS

I am currently exploring the process of hosting static js and css files using NextJS. My journey began with creating a react app through create-react-app, where I developed an App component before executing the npm run build command. This resulted in the ...

Guide on incorporating jQuery library files into existing application code with the npm command

Recently, I used a node JS yo ko command to create a single-page application using Knockout-JS. Following that, I proceeded to install jquery packages using the command npm install jquery The installation was successful. However, my current goal is to in ...

Send an array and a single string to a PHP script using an Ajax request

I am attempting to incorporate the code snippet below: var flag = new Array(); var name = $("#myselectedset").val(); $.ajax({ type: 'post', cache: false, url: 'moveto.php', data: {&a ...

Bidirectional updates in AngularJS with CSS styling

On the backend, certain HTML elements store their position and size persistently and retrieve them when the page loads. These elements can be dragged and resized by users, with any updates needing to be saved on the backend for consistency across sessions. ...

What is the method for identifying modules that rely on a specific module?

Is it possible to view all dependencies modules of a specific module, similar to this: npm-remote-ls <module-name> But how can we see the modules that depend on a particular module? Any help would be appreciated. Thank you. ...

Tips for splitting lengthy text into multiple lines in Vue

Vue is being used to display a line which appears lengthy when displayed in one line. I'm interested in splitting this long line into multiple lines automatically. Can someone guide me on how this can be achieved? <span class="text-xs"> ...

dividing an HTML string into individual variables using JavaScript

How can a string be split in pure JavaScript (without using JQuery/dojo/etc) in the most efficient and straightforward way? For example: var tempString = '<span id="35287845" class="smallIcon" title="time clock" style="color:blue;font-size:14px;" ...

jquery function context

I'm having trouble grasping function scope in this scenario. When a button is clicked, it triggers a dialog box with a textarea inside displaying a URL that can be copied for camera setup. <button id="axis-details" onclick="apikey('<?php e ...

Inspect each element of the array individually, and issue a warning if any two elements are identical

Trying to set up an add to cart feature and feeling a bit lost. Unsure if I should be using cookies or local storage for this task, as I'm familiar with localstorage but not sure if it's the best approach. Working with vue.js using Vuex. Ideally, ...

What is the best way to incorporate AJAX with Node.js?

After testing the Hello world program with Node.js, I can confirm that it is working perfectly. Here are the file details: index.html socket.js To run in command prompt: node socket.js I also experimented with ajax calls in Node.js using the same hel ...

Issue with Context Menu Not Triggering on Dynamically Added Elements in JQuery

Check out the JSFiddle Demo Within my email sidebar, I implemented a custom right-click feature that allows users to add new sub-folders. The code snippet below demonstrates how this functionality works: if ($(this).hasClass('NewSubFolder')) { ...

I've encountered some issues with importing pagination from modules after installing SwiperJs

Having some issues with importing pagination from modules in SwiperJs for my nextjs project. The error message "Module not found: Package path ./modules is not exported from package" keeps popping up. I have tried updating the module to the latest version ...

Challenge with Context Api state not reflecting the latest changes

Hey there, I've got this function defined in AuthContext.js: let [authTokens, setAuthTokens] = useState(null) let [user, setUser] = useState(false) let [failedlogin, setFailedlogin] = useState(false) let loginUser = async (e) => { ...

What is a more efficient way to differentiate a group of interfaces using an object map instead of using a switch statement?

As someone still getting the hang of advanced typescript concepts, I appreciate your patience. In my various projects, I utilize objects to organize react components based on a shared prop (e.g _type). My goal is to automatically determine the correct com ...

Send data in JSON format along with an identifier using Jquery AJAX

I am having trouble sending JSON data along with 2 IDs using a jQuery AJAX post. Despite my efforts, I can't seem to get it working. Here is the code snippet in question: try { var surveyID = localStorage.getItem("surveyId"); var userDetails ...

Generating a two-dimensional array and setting its values in JavaScript

I need assistance with creating and initializing a two-dimensional array in JavaScript within an AngularJS application. My current approach is as follows: $scope.invalidVote = []; for (var i = 0; i < $scope.arry1.length; i += 1) { $scope.answersCou ...

What is the best method for deleting scripts to optimize for mobile responsiveness?

My current plugin.js file houses all my plugins for responsive design, but it is unnecessarily large and cumbersome for mobile devices. I am considering creating two separate plugin.js files to toggle between for mobile and desktop views. What are the r ...

Retrieve the variance between two arrays and store the additions in AddedList and the removals in RemovedList using typescript

I am still getting the hang of Typescript and I am trying to figure out the best solution for my issue. I have two arrays, A and B, and I need to identify the difference between them in relation to array A. The goal is to separate the elements that were ad ...

What purpose does this particular express variable serve?

I am currently diving into the world of JavaScript, with a basic programming background to boot. However, I have always stumbled when it comes to grasping OOPs concepts. For instance, we start by importing what I believe is the express module through &apo ...

Implementing JavaScript Functions to Trigger Control Key and Plus/Minus Events

In my project, I have a unique set of selectors called A+. By clicking on the A+ button, it has been programmed to initiate the control plus event. Similarly, within the same interface, I also have an A- button that activates the control minus event when ...