Issue with Vue.js - GET response not being stored in this.data

<!DOCTYPE html>
<html>
<head>
  <title>Welcome to Vue</title>
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
  <div id="app">
    <button v-on:click="sendTime">Load</button>
  <div v-for="user in users">
    <p>{{ user.username }}</p>
  </div>
</div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
new Vue({
el: '#app',
data: {
  users: [
    { username: "billy" },
    { username: "ryan" }
  ],
},
methods: {
  sendTime : function () {
    axios.get('/api/users')
  .then(function (response) {
    console.log(response.data);
    this.users = response.data;
  })
  .catch(function (error) {
    console.log(error);
  });
  },
}
})
</script>

</body>
</html>

console.log returns -

Array [ Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, 15 more… ]

Struggling to assign the returned array to 'this.data' after button click event. Need help with data assignment issue!

Answer №1

fetchData(){
  axios.get(...).then(function(response){
    this.data = response.data;
  }.bind(this));
}

For more information, check out How to handle 'this' inside a callback function?

Answer №2

To ensure you have access to the Vue object, it's helpful to store a reference to it and then utilize that reference in your callback function.

methods: {
  fetchUsersData : function () {
    var vm = this;
    axios.get('/api/users')
      .then(function (response) {
        console.log(response.data);
        vm.usersList = response.data;
      })
      .catch(function (error) {
        console.log(error);
      });
  },
}

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

Error encountered while using XLSX.write in angular.js: n.t.match function is not recognized

I've encountered an issue while trying to generate an .xlsx file using the XLSX library. The error message I received is as follows: TypeError: n.t.match is not a function at Ps (xlsx.full.min.js:14) at Jd (xlsx.full.min.js:18) at Sv (xlsx.full.min ...

The asynchronous error handling wrapper is not functioning correctly

My goal is to create a wrapper for the express callback function displayUsers(). This will help in adding error handling logic to avoid using try catch blocks everywhere. An issue I am facing is that the fn() function actually executes before being invoke ...

The usage of an import statement is not permissible outside of a module

Having some trouble using the mathjs library to calculate complex solutions for the quadratic equation. No matter how I try to import the library into my code, I keep encountering errors. Initially, I attempted this method: At the top of my root.js file, ...

JSON string inside a string-type in AWS model

My goal is to create a basic model that can accept a JSON string instead of defining all variables/elements upfront. The model will have an "options" element which will hold a JSON string. Below is the structure of my model. { "$schema": "http://json-sch ...

Developing a unique JavaScript object by extracting information from a jQuery AJAX response

Is there a recommended approach for creating a custom JavaScript object that contains data retrieved from a jQuery AJAX request? I'm considering two methods, but unsure which is the most appropriate. The first method involves including the AJAX reques ...

What is the most effective way to organize an array according to a key function that is computationally intensive?

After posting this question regarding sorting an array with a key function, it became evident that utilizing a comparison function was inevitable. The challenge at hand includes: Having a resource-intensive key function that needs to be transformed into ...

Managing various registers using Vue.js and an API endpoint

I am faced with a scenario where I have an application containing client data stored in a database. The number of clients can vary greatly, currently standing at 200, but potentially reaching up to 2 million. Additionally, there is a web service that inter ...

Mapping memory for FirefoxOS is like equivalent strides

Is there a way to create a memory mapped file in FirefoxOS, Tizen or other pure-JS mobile solutions? In the scenario of a mobile browser where you have large amounts of data that can't fit in RAM or you prefer not to load it all at once to conserve R ...

Struggling to clear items from input field within AngularJS

I'm currently facing an issue where I am unable to delete data from an input field. var myApp = angular.module('myApp',[]); myApp.controller('MyCtrl', function MyCtrl($scope) { $scope.items = [ { name: & ...

Absolute positioned content causing unexpected spacing on top of relative positioned content

I've been experimenting with a fantastic technique by Chris Coyier for implementing full page video backgrounds with content scrolling over the video. However, I've encountered an issue where there's an unexpected gap to the right in Windows ...

Guide on creating a Vue and Node application for deployment on a server?

What is the best way to deploy a JS app (Vue + Node) on my office server? Should I combine Vue and NodeJS in one build or create separate builds for each? Kindly provide a comprehensive explanation. ...

Transforming Google Maps from using jQuery to AngularJS

If I have a Jquery google map with find address and routing system, my goal is to convert it to an angular google map with more options. The current Jquery google map code looks like this: var directionsDisplay = new google.maps.DirectionsRenderer({ d ...

Is there a way to transform a JavaScript array into JSON format in order to use it as the returned data from a RESTful API

Currently, I am exploring how to efficiently convert an array of arrays into a JSON string for retrieval through a RESTful API. On my server, data is fetched from a database in the format: {"user":"some name","age":number ...

Notification from HTML code within Django

In my Django project, I am trying to implement an alert. I am sending data from views.py to singup.html in order to display an alert based on certain conditions. However, initially the alert variable in HTML is not assigned a value. It is only after click ...

Leveraging an external JSON file within a Vue application

A friend of mine isn't very tech-savvy, so I'm building a website for him with an idea to simplify the process. I plan to create a JSON file to store all the text and image paths, allowing him to easily make changes without needing to delve into ...

Sorting Object Values with Alternate Order

Is there a way to sort a JSON response object array in a specific order, especially when dealing with non-English characters like Umlauts? object { item: 1, users: [ {name: "A", age: "23"}, {name: "B", age: "24"}, {name: "Ä", age: "27"} ] ...

Mastering the art of correctly utilizing JavaScript promises in the context of Ionic and Cordova

Here is the code snippet for Login.ts: export class LoginPage { public version:string; constructor(public navCtrl: NavController, public navParams: NavParams, private appVersion: AppVersion) { this.appVersion.getVersionNumber().then((val) => { ...

Is there a way to utilize the reset() function within an input form?

Is there a way to automatically reset the textbox when submitting a value? Below is my code: <!DOCTYPE html> <html> <body> <ul id="myList"> </ul> <input type="text" id="myText" value="&q ...

What goes on behind the scenes of Angular interpolation with scripts?

I set up a variable called test = '<script>alert()</script>'. I then inserted this variable into an Angular component using interpolation like so: <div>{{ this.test }}</div>. However, instead of rendering properly, it just ...

JSONP error: "Syntax error - token not expected"

While attempting to perform a JSONP AJAX request, an error was thrown: Uncaught SyntaxError: Unexpected token I'm puzzled about what is wrong in my code. Can someone assist? $.ajax({ url: 'http://api.server32.trustklik.com/apiv1/website/ ...