Working with Vue.js and Axios: Extracting data from a nested Axios response

I am currently working on a project that involves Vue.js, TypeScript, and Axios. My main focus is on creating a complex ApiRequest. Unlike the traditional method of fetching data using axios directly in the component, I wanted to find a more maintainable solution for a large-scale project.

Instead of the conventional approach, I decided to create an "ApiService.ts" file where I defined the GET function:

import axios from "axios";

import { ApiRequest } from "../models/api/ApiRequest";
import { HttpMethod } from "../enums/HttpMethod";

const httpClient = axios.create({
    baseURL: "http://localhost:9090"
});

class ApiService {

    async get<T=any>(url: string): Promise<T>{
        return await this.perform<T>({
            method: HttpMethod.GET,
            url,
        });
    }

    private async perform<T = any>(request: ApiRequest): Promise<T> {
        try {
            const response =  await httpClient({
                method: request.method,
                url: request.url,
            });
            console.log(response.data)
            return response.data
        }   catch (error) {
            const message = error.response
            ? error.response.data.message
            : error.message;

            throw Error(message);   
        }
    }
}

export const apiService = new ApiService();

I then imported it into my original file:

data (){
    return {
        users:[]
    }
},

methods: {
    getUsers : function() {

    this.users = apiService.get("/Users");
    }
}

Finally, I called the function to populate the users Array in the same file as follows:

<button @click= "getUsers"> Click here to get users </button>

<div> {{users}} </div>

However, when I click the button, I encountered an unexpected behavior which you can view here.

Essentially, my users Array contains a "Object Promise" instead of the actual user data. Can anyone provide insight on how to display the user data correctly in my users Array rather than just a promise object? Additionally, what exactly is this "object Promise"?

Thank you!

Answer №1

The get function returns a Promise because it is an async function. This is why when you call apiService.get(), you receive a Promise object. Make sure to use async/await in your code to handle this correctly.

methods: {
    getUsers : async function() {
        this.users = await apiService.get("/Users");
    }
}

If you want to display the users, you can do something like this:

<button @click= "getUsers"> Click here to get users </button>

<div
  v-for="(item, index) in users"
  :key="index"
>
  {{ `Name: ${item.name}, Address: ${item.address}` }}
</div>

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

Can Vuex getters be utilized in a Vue component's computed property?

I have various variables in my vuex-store, such as loggedIn. I need to access this variable from the computed section of my component to filter an array based on its value. Here is how I am trying to implement it in my code: <td v-for="(item, index) i ...

Exploring the issue with Vuex within the beforeRouteEnter function

Within the galaxy project, there is a Vuex function named "asyncValidateToken" that verifies the user's login status in the system. This function can be found in the file "src/store/index.js". The code within this file includes: import Vue from ' ...

What is the process for verifying your identity with Google OAuth2 in Vue.js?

Being new to vue.js, I have been struggling with a particular issue for days. Despite knowing that there are a few plugins available, such as: vue-google-auth and vue-google-signin-button and vue-authenticate Unfortunately, none of these plugins come ...

Retrieve the list of all members in the Telegram group

Is there a way to retrieve all users from a Telegram group using the Telegram bot API in Node.js? While I'm familiar with the getChatAdministrators method, it seems like there isn't a specific method for getting all group members. I would apprec ...

Retrieve specific elements from an array based on the other elements present in the array

I am working with a result set that consists of various combinations from the following data structure: [ ["1st", "FELONY"], ["2nd", "FELONY"], ["3rd", "FELONY"], ["1st", "MISDEMEANOR"], ["2nd", "MISDEMEANOR"], ["3rd", "MISDEMEANOR"]] For example, it co ...

The Chrome equivalent of -moz-user-focus

We have a custom model dialog control that we use for all popups on our web pages. When this dialog is initialized, we use jQuery expose to gray out the rest of the page. To prevent selection on the grayed-out area, we apply the following styles to the mas ...

Node.js encountering issue with printing an array

Here is the code snippet from my routes file: router.get('/chkjson', function(req, res, next) { req.getConnection(function(err,connection){ var ItemArray = []; var myset = []; var query = connection.query('SELEC ...

Find the differences between two arrays and eliminate any matching items

In my Vue project, I am working with two arrays. The first array, TempId, contains the following data: [{"id":47},{"id":45},{"id":48}] The second array is called multiprices and it looks like this: multiprices: [ { ...

Angular - ng-repeat failing to update when nested array is modified

Utilizing ng-repeat to render data fetched via a GET request that returns an array. HTML <div ng-controller="candidateCtrl" > <div class="table-responsive"> <table class="table table-striped"> <thead> ...

What is the best way to incorporate component-specific CSS styles in React?

This is the layout that I am attempting to replicate (originally from react-boilerplate): component |Footer |style.css |Footer.js In Footer.js, the styles are imported in a very elegant manner like this: import React from 'react'; im ...

Challenges arise when attempting to merge declarations in Typescript involving passport, passport-local, and express-session

I'm currently facing challenges trying to integrate passport, passport-local, and express-session with Typescript. After installing all four necessary libraries - @types/passport, @types/express-session @types/passport-local, and @types/express - I in ...

Using JavaScript to alter CSS styles with dashes

Currently, I'm delving into the world of manipulating CSS using JavaScript: img.style.borderRadius = "100%"; img.style.border = "9px solid #ffffff"; img.style.boxShadow = "0 0 5px #00000070"; img.style.margin = "20px"; I'm wondering how to chan ...

The collapsing html menu remains in place instead of navigating to the designated id

After clicking on a link, my jQuery code moves the "a" element to the specified id in the href attribute of the link. Below is an HTML code snippet: <nav class="navbar w-100 align-items-center navbar-expand-md fixed-top bg-white border-bottom shadow-s ...

What is the reason behind Azure Identity's choice of Browserflow over nodeflow for integration in my Next.js application?

Embarking on my inaugural project with Next.js, I find myself in unfamiliar territory. Rather than joining existing projects, I am constructing apps from scratch, encountering a challenge with Azure Identity along the way. Upon delving into the node module ...

Tips for passing the indexes of an array within nested ngFor loops in Angular

I have a 2D grid in my component that is created using nested ngFor loops, and I want to make certain grid elements clickable under specific conditions so they can call a function. Is there a way for me to pass the index of the clicked array element to the ...

What is the best way to transfer data to another PHP file using AJAX?

Being new to ajax and lacking significant knowledge about it, I have created two PHP files - six.php and six-cuf.php. Upon user input in six.php and submission, this will trigger a call to six-cuf.php using ajax for the calculation. However, while executi ...

405 Method Not Allowed - Compatible with all devices except for iOS Safari

Recently, I've been working on an application using AngularJS to track and submit statistics to a Google Apps Script for processing. While everything functions flawlessly on my computer in both Chrome and Firefox, encountering errors on the iPad has b ...

Ways to avoid encoding Unicode characters in JavaScript programming

When I retrieve data from an API, I receive a STRING like this: [ { "reason": "Invalid address", "email": "j\u00c3\u00a9r\u00c3\u00b4mel\u00c3\u00a4ufer@com" }, { "reason": "Invalid address", "email": ...

Tips on incorporating a fresh item into a expansive tree view using a recurring function or action - specifically geared towards the MUI React JS Tree View component

I am looking to implement a function or action that allows for the dynamic addition of new items to a tree view in MUI. The goal is to be able to click on a tree item and have it add another item, repeating this process as needed. <TreeView ...

Anticipating the execution of a loop and retrieving a value in Node.js

I am currently diving into the world of Node Js programming. I understand that javascript does not follow a sequential order and executes code synchronously which has led me to struggle with async calls. Here is the issue I am facing: Within my app.get(&a ...