Issue encountered while retrieving information using Axios in a Vue.js application

Currently, I am in the process of developing a full stack application using Vue.js and Fastify.js (a Node framework). The Vue app is supposed to retrieve data from the API I created and display it in the browser console. However, I am encountering an issue where the data is not rendering within the app itself. I even attempted to load it using the mount function, but to no avail.

Below is the complete code I am working with:


const app = new Vue({
  el: '#app',
  data: {
    infos: [{
      name: 'Vue',
      age: 19,
      imageUrl: 's3.aws.amazon.com'
    }, {
      name: 'Vue 2',
      age: 20,
      imageUrl: 's3.aws.amazon.com2'
    }],
    msg: 'Hello Vuejs!'
  },
  methods:{
    getData: () => {
      axios.get('http://localhost:3000/getData')
        .then((result) => {
          this.infos = result.data;
          console.log(infos);
        })
        .catch((err) => {
          console.log(err);
        });
    }
  }
})

{{msg}}


Name: {{info.name}}
Age: {{info.age}}
Image: {{info.imageUrl}}

This image displays what is currently being rendered: The default values are shown, and the array is logged on the right.

For the complete code, please visit: https://github.com/siddiquiehtesham/fullstack-vue-nodejs-api

Answer №1

Your axios request is facing an issue where the this keyword is not properly bound to your Vue instance.

To resolve this, you can use arrow functions to maintain the correct context:

getData: function() {
  axios.get('http://localhost:3000/getData')
  .then(result => {
    this.infos = result.data
    console.log(this.infos)
  })
  .catch(err => {
    console.log(err)
  })
}

Alternatively, you can create a self variable before making the request:

getData: function() {
  let self = this
  axios.get('http://localhost:3000/getData')
  .then(function(result) {
    self.infos = result.data
    console.log(self.infos)
  })
  .catch(function(err) {
    console.log(err)
  })
}

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

Is there a way to verify the presence of a complete object by using a specific key in JavaScript

As I loop through my data, I only want to assign a random number to a fontObj if it is unique. A typical fontObj consists of: { postscript: "Calibri", style: "Bold", family: "Calibri" } In my code, I aim to iterate ...

Error with JavaScript callback functions

After creating a POST route, I encountered unexpected behavior in the code below. The message variable does not display the expected output. app.post("/", function (req, res, error) { var message = ""; tableSvc.createTable("tableName", function (error ...

The .forEach() method in Javascript is not suitable for DOM nodes as they are subject to change during the iteration

Having an issue with moving all DOM elements from one node to another, I initially used this code: div.childNodes.forEach((n) => me.container.appendChild(n)); However, I noticed that only half of the nodes were being copied. It seems that the problem ...

Difficulty replicating 3 input fields using JavaScript

Combining the values of 3 input fields into 1 Displaying 'fname mnane lname' in the fullname input field. Then copying the fullname value into another input field called fullname2. Check out the code below for both HTML and JavaScript implemen ...

working with JSON array information

I have a JSON array retrieved from a database that I need to manipulate. Currently, it consists of 8 separate elements and I would like to condense it down to just 2 elements while nesting the rest. The current structure of my JSON looks like this: { "i ...

The Powerful Duo: JavaScript and Regex

Having some issues with the code snippet below, I know there's an error in my code but I can't seem to figure out what it is (tried enclosing the code in quotes but that didn't work...) var Regex = require('regex') var regex = new ...

Angular's getter value triggers the ExpressionChangedAfterItHasBeenCheckedError

I'm encountering the ExpressionChangedAfterItHasBeenCheckedError due to my getter function, selectedRows, in my component. public get selectedRows() { if (this.gridApi) { return this.gridApi.getSelectedRows(); } else { return null; } } ...

"Vue: The persistent issue of props returning as undefined continues to trouble developers

While checking my Root and child component (Topbar), I keep finding that the foo prop is undefined in each one. It's perplexing because I have defined it properly. app.js window.Vue = require('vue'); Vue.component('Topbar', ...

Issue with Webpack failing to bundle a custom JavaScript file

Here is the structure of my directory: Root -dist -node_modules -src --assets --css --js --scss --index.js --template.html --vendor.js package-lock.json package.json postcss.config.js tailwind.config.js common.config.js development.config.js production.co ...

Using AngularJS to send a $http.post request with Paypal integration

This form utilizes the standard PayPal format for making purchases. <form action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_xclick"> <input type="hidden" name="business" value="<a href= ...

Efficiently Fill JQUERY Mobile Multi-Pages with Dynamic Content

A Question for JQUERY Mobile Beginners: In my basic JQUERY Mobile application, I have a simple setup with two pages. When the user navigates to PAGE2, I need to make an AJAX call to retrieve a JSON object that contains a list of people along with their DB ...

Aggregate the values in an array and organize them into an object based on their frequency

I have an array of information structured like this: 0: { first: "sea", second: "deniz", languageId: "English-Turkish"} 1: { first: "play", second: "oynamak", languageId: "English-Turkish&qu ...

attempting to fulfil a promise through a resolution

I am currently attempting to use a resolve with a promise in response to an issue with filters that I am currently tackling. However, my resolve function is not yet functioning as expected. I have decided to implement this approach based on advice I recei ...

Console displaying API results but not appearing in browser window

class App extends Component { state = { data: '' } componentDidMount() { axios.get(`https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=wikipedia&utf8=&format=json`) .then(res => ...

Using Angular 6 to import GeoJSON into a Leaflet map

I am facing an issue while trying to import a GeoJson file into Leaflet in my Angular app version 6. Although the geojson is being successfully drawn on the leafletmap, I am encountering an error that is preventing me from building my app. Is there anyone ...

Tips for crafting paragraphs that double as sieves

I'm trying to simplify and shorten this code. I have three HTML paragraphs acting as filters: "all", "positive," and "negative", referring to reviews. Each has a corresponding div for reviews: "allcont", "poscont", and "negcont". Clicking on any of th ...

Understanding Json data using Jquery

I am currently learning about Jquery, Ajax, and JSON but I am having difficulty with parsing Json data. Despite researching extensively on stackoverflow Parsing JSON objects for HTML table Access / process (nested) objects, arrays or JSON Parse JSON in ...

Utilize Vue CLI 3 to enable popups in arcgis API JS

I've been attempting to enable popups from the ArcGIS API JS to show using the Vue-CLI 3 framework. Unfortunately, even with a simple sample code, I'm unable to make it function properly. Below is the code initially written in vanilla JS: <!DO ...

Cannot see the created item in Rails application when using RSpec, Capybara, Selenium, and JavaScript

Currently, I am in the process of developing a web store. The key functionality is already implemented where all products are displayed on one screen along with the list of ordered items. Whenever a product is selected for ordering, it should instantly app ...

Getting the value of a CSS variable under <script> in Vue.js

I am working on implementing a Doughnut chart using chartJs in my application. However, I want to set the color of the chart within the <script> tag and retrieve the color from theme/variables.css. In the current code snippet below, there is a hardc ...