The console is displaying 'undefined' when attempting to render the JSON response in Vue

In my vue.js application, I'm trying to display text using TypeScript. Here is an example of the JSON response:

{
    "data": [
        {
            "firstName": "Foo",
            "lastName": "Smith"
        },
        {
            "firstName": "Mike",
            "lastName": "vue"
        },
        {
            "firstName": "go",
            "lastName": "lang"
        }
    ],
    "metadata": "none"
}

Using TypeScript:

export interface TestResponse {
    firstName:string;
    lastName:string;
}

Axios call:

const request: AxiosInstance = axios.create({
    baseURL: url.baseUrl,
    headers: {
        'content-type': 'application/json',
    },
    //params: {base64_encoded: 'true', fields: 'stdout'},
});

export const api = {

    async getTest() {
        try{
            return await request.get<TestResponse>("/v1/test")
                .then(res => {
                    console.log("lastname " + res.data.lastName);
                    return res.data
                })
        }catch (err) {
            console.log("error" + err);
        }
    },

}

However, it always shows undefined. I have tried using TestResponse[] and Array<TestResponse> without success.

Instead of getting an array as expected, I receive the error message:

Cannot read properties of undefined (reading 'data')

export default {
    name: "Test",

    setup() {

        const firstName = ref('');
        const lastName = ref('');

        const submit = async () => {
            try {
                const response = await api.getTest()

                if (response != null) {
                    firstName.value = response[0].data.firstName
                    lastName.value = response[0].data.lastName
                    console.log("I am a name " + response.lastName)
                }
            } catch (error) {
                console.log('Error while getting the response:', error)
            }
        }

        return {
          firstName,
          lastName,
          submit
        }

    },

};

Answer №1

Upon reviewing your code, I have identified two main issues. Firstly, the type of your response object needs to be considered. Secondly, the way in which you are executing your request may need adjustment.

In regards to the response object, it appears that the content of the response body is located within res.data. However, it seems that your API also returns a field named 'data'. Therefore, you might need to access the data by using res.data.data or update the body returned by your API accordingly. Based on the example JSON response provided, the correct Typescript type would be:

export interface TestResponse {
  firtName: string
  lastName: string
}

export interface TestResponseRO {
  data: TestResponse[]
  metadata: string
}

If you are utilizing await, there is no need to use .then. Instead, you should structure your code as follows:

async getTest() {
  try {
    const res = await request.get<TestResponseRO>("/v1/test");

    console.log(res.data) // This should display '{"data": [your array], "metadata": "none"}'

    return res.data 
  } catch (err) {
    console.error(err)
  }
}

If errors persist, I recommend testing the API endpoint using tools like curl or Postman to ensure proper functionality. Additionally, consider utilizing axios as an HTTP client, as it offers more flexibility compared to request.

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

UI-grid: Triggering a modal window from the filter header template

Is there a way to create a filter that functions as a simple modal window triggered by a click event, but can be displayed on top of a grid when placed within the filterHeaderTemplate? I have encountered an issue where the modal window I created is being ...

Ever since updating my Node JS, the functionality of the MaterializeCSS carousel methods has ceased to work

Recently, I encountered some issues with my React project that features a materialize-css carousel. The problem arose after updating my nodeJS version from 14.8.1 to 16.13.0. Specifically, these errors kept popping up: TypeError: Cannot read properties o ...

Retrieving information received from an XML HTTP request in node.js

Currently, I am transmitting text data from a textbox to a node.js express server using XMLHttpRequest: var text = document.getElementById("textBox").value; console.log(text); var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Fire ...

Forwarding parameter data type

I am facing an issue with 2 navigation points leading to the same screen 1. this.router.navigate([this.config.AppTree.App.Module.Details.Path], { state: { data: { id: this.TableId } } }); this.router.navigate([this.config.AppTree.App.Module.Details.Pa ...

Exploring the DOM through the Chrome developer console

So, when I input the following code in my Chrome console: document.getElementById('scroller') I receive output similar to this: <div class="blah" id="scroller>...</div> However, if I pause a script and add a watch with the same ex ...

What are the TypeScript types needed for a React component that accepts an array of objects as a prop?

I am currently working on a React component that includes a prop named propWhichIsArray. This prop is expected to be an array of objects. Each object in the array will contain properties such as id (an ID) and text (a string). How do I properly define this ...

To successfully use Router.use(), you must provide a valid middleware function. How can we resolve this issue of passing undefined as

I have developed a CRUD application using node.js and now I need to incorporate another node project as a microservice. To send HTTP requests to the other node project, I am utilizing the axios npm module. However, when I run the code, I keep encountering ...

Loop through associative array in PHP using JQuery

I have a PHP associative array and I am using JQuery AJAX to retrieve the result array. My issue arises when passing the result to jQuery and attempting to loop through and extract each Sequence, Percent, and Date. I need to store this extracted data in a ...

What could be causing my bounce animation to begin 50 pixels higher than its intended starting point?

Trying to create a bouncing effect on text Check out my attempt here. It seems like the bug is in this area. @keyframes bounce{ 0%, 40%{ transform:scale(2,.5) translate(0,100px); } 45%,55%{ transform:translate(0,-50px); } 55%, 100%{ ...

How is babel-loader / tsc compiler able to distinguish between importing a package for its types only and for its functionalities?

Currently, I am integrating Typescript into my project. During this process, I made an interesting discovery. In the App.tsx file below, you will notice that I needed to use import firebase from "firebase/app" in order to access the firebase.ap ...

Modify mesh in three.js scene

Is there a way to dynamically change a mesh in a group triggered by a button click? I am loading an external .obj file: loader.load( obj, function ( object ) { createScene( object, mod.tipo, pid, cor.replace("#","0x") ); }); and adding it to a gro ...

NodeJS unexpectedly exhibiting peculiar array functions

Within my NodeJS code, I have the following implementation: /* server.js */ 'use strict'; const http = require('http'), url = require('url'); METHODS = ['GET','POST','PUT','DELETE&a ...

What is the best way to generate a ul-li structure using JSON input and jQuery?

There is a JSON variable present: var links=[{"text":"Home","href":"http://home.com","icon":"fas fa-home","target":"_top","title":"My Home","children":[{"text":"home2","href":"home2.com","icon":"fas fa-chart-bar","target":"_self","title":"home2","category ...

Executing a JavaScript function to trigger a PHP script that saves data into a MySQL database

I have a button in my HTML file that, when clicked, should insert data into a database and then reload the page. I am calling a JavaScript function within the onclick event to handle this. Below is the JavaScript function: function grandFinale() { i ...

Is using float:right making the jquery slide toggle dropdown div (triggered by hover) appear glitchy?

Utilizing jQuery's slidetoggle and hover functions, I have successfully implemented a dropdown feature in my div. Within this div, there is various information displayed including the date, a note counter, and three buttons. The first two are Tumblr ...

localStorage is functional on desktop devices; however, it does not work on mobile devices running iOS version 12

After developing a basic Todos application using React, I decided to introduce the use of localStorage to maintain data persistence between page reloads. Below is an overview of how I implemented it: loadStateFromLocalStorage() { for (let key in this.st ...

Enable AJAX to dynamically load pages without caching

I am currently using an ajax function to refresh a specific division on a webpage with HTML content. <script> $('#scene_container').load('scene.html', function () { cache: false }); </script> ...

Issue with displaying leaflet.js map on Node.js using Express and Jade template

My goal is to display a map on a webpage using a Jade template. The template code is as follows: html head script(src='http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js') link(rel='stylesheet', href='http://cdn.leafletjs.c ...

Monitoring of access controls on Safari during uploads to S3

Safari 10.1.2 Encountering an issue intermittently while attempting to upload PDF files to S3 using a signed request with the Node aws-sdk. Despite working smoothly 90% of the time, have been pulling my hair out trying to resolve this problem. Could it be ...

activate a CSS-only modal with JavaScript

Is it possible to trigger a pure CSS modal using JavaScript (jQuery) without the need for a label, so that it activates when a user visits a page? http://jsfiddle.net/h84nubzt/ <label class="btn" for="modal-one">Example</a> <!-- Modal ...