Navigating JSON/API data within a Vue.js component template: step-by-step guide

I've successfully implemented a code snippet that renders a list of songs here: https://jsfiddle.net/jeremypbeasley/guraav4r/8/

var apiURL = "https://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user=thisisheroic&period=7day&limit=6&api_key=3cbc1a3aa903935d08223263bcc3ba0b&format=json";

new Vue({
  el: '#demo',
  data: {
    commits: null
  },
  created: function () {
    this.fetchData()
  },
  methods: {
    fetchData: function () {
      var xhr = new XMLHttpRequest()
      var self = this
      xhr.open('GET', apiURL)
      xhr.onload = function () {
        self.commits = JSON.parse(xhr.responseText)
      }
      xhr.send()
    }
  }
})

This method works flawlessly for rendering the list of tracks, however, when I try to implement the same logic inside a component, it breaks and throws two errors:

Error messages I receive are as follows:

[Vue warn]: The "data" option should be a function that returns a per-instance value in component definitions.
along with an error indicating that commits.toptracks is undefined.

Here's my unsuccessful attempt within a component context:

Vue.component('manage-posts', {
  template: '#manage-template',
  data: {
    commits: null,
  },
  created: function () {
    this.fetchData()
  },
  methods: {
    fetchData: function () {
      var xhr = new XMLHttpRequest()
      xhr.open('GET', apiURL)
      xhr.onload = function () {
        this.data = JSON.parse(xhr.responseText);
        console.log(JSON.parse(xhr.responseText));
      }
      xhr.send()
    }
  }
})

I would greatly appreciate any assistance in understanding these errors and figuring out where I may have gone wrong in my approach!

Answer №1

Initially: Instead of defining the data property as an object literal, consider using a function that returns an object literal upon execution. Here's an example:

...
data: () => ({
    commits: null
}),
...

Next: When working with the fetchData function, be cautious when assigning to xhr.onload. There is a possibility that this might refer to the xhr object at the time xhr.onload is executed.

Note: You may find vue-resource to be a more user-friendly alternative to using XMLHttpRequest.

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

Converting form input to JSON and then parsing it into an object

I'm currently working on converting form data to update a JSON object upon submission. Here's my progress so far: var app = { slidePreviews: "", selectedTheme: "", slideDuration: 7000, slides: [] }; $(document).ready(function() ...

Is there a way to incorporate hyperlinks into the Application column of my v-data-table component?

When loading data table from the database, I have included links along with the names of the Applications. However, I only want to display the Application name and open the corresponding link when clicked. headers: [ { text: 'Name&a ...

What is the process for inserting an image into a table using el-table and el-table-column components in Vue.js while utilizing ui-elements?

I'm new to Vue.js and successfully built a basic table using the ui-element. The el-table element was utilized for constructing the table, with columns displayed using el-table-column and prop (see code below). Now, I want to incorporate images/avatar ...

Encountering Internal Server Error when C# WebMethod communicates with JavaScript AJAX call

I've encountered an issue where my AJAX call to a C# WebMethod is not returning the expected result. Instead, it keeps showing an "Internal Server Error" message. A button triggers a JavaScript function: <button id="btn" onclick="Create();">fo ...

Incorrect positioning of arrow in OverlayPanel (PrimeVue)

I have been experimenting with overlay panels in the PrimeVue framework, and I've encountered a peculiar issue that I can't seem to resolve. On the demo page, the arrow is positioned on the left side: https://i.stack.imgur.com/Gn3qe.png Howeve ...

Display or conceal div elements using JavaScript

Is there a way to hide certain divs when clicking on a specific div box? Clicking on the box will trigger the hiding of some application divs. See the first image below: When the boxes are hidden, the other divs will readjust in place of the current divs ...

How can we verify the validity of URLs based on their length, presence of capital letters, and specific whole words?

I'm currently working on a piece of code that verifies the URL provided by users during sign-up for my application. I want to implement the following restrictions: URL must be at least 3 characters long No capital letters allowed Avoid certain words ...

Guide for inserting personalized buttons onto a map with the Bing Maps 6.3 Ajax Control

Looking to enhance a Bing Map with custom buttons for more interactive functionality? I'm interested in creating a custom dashboard on the map that would allow users to toggle different information or colors displayed on specific pins or polygons by s ...

Guide to retrieve the file name into a text box upon selection (Avoid displaying as c:/fake path/)

I am trying to achieve the functionality where after choosing a file in a file input, the file name is automatically displayed in a text box named file_name without needing to click or submit any button. Unfortunately, I have been unable to find the correc ...

Having trouble with the date format in the highCharts range selector?

I am encountering an issue while trying to implement the rangefilter feature with HighCharts. The start and end dates are appearing incorrect, indicating that my date is not being recognized properly. My x-axis consists of unique dates as categorical valu ...

Can you provide guidance on decompressing SVGZ files using JavaScript?

I'm currently working on implementing a high-resolution world map using SVGZ instead of the standard SVG format, aiming to provide my users with a more intricate and detailed visualization. Although I have experimented with utilizing js-deflate to de ...

Exploring the concept of inheritance in JavaScript and Angular programming

Currently, I am working on a project called "hello world" and it involves two HTML pages named "configuration.html" and "add configuration.html". Each page has its own controller defined as follows: angular.module('MissionControlApp').controller ...

The error message "Uncaught TypeError: Cannot read property '0' of undefined" is triggered when using toDataURL

Recently diving into the world of JavaScript and facing a perplexing error. I must be overlooking some fundamental concept... apologies in advance. Here is the issue at hand. In my HTML file, this snippet of code is present: <div> <script type= ...

Adding a PDF generated from an HTML div to an email using Java

I am looking for a solution to convert the contents of an HTML div tag into a PDF file while preserving its associated CSS. This is essential as I will be using Java on the back-end to send emails, and I need to attach the PDF with the CSS intact when send ...

AngularJs Number Formatting: A Step-By-Step Guide

Is there a way to format a number from 10000 to 10,000.00 using only HTML and the ng-Model directive, without involving the controller file? I attempted to achieve this in the controller file through logic, but it always returns the number in the "10,00 ...

How long does it take for Google Docs to respond to a JSON request

I'm facing an issue with a Google Docs spreadsheet that I have set to publish as RSS -> JSON. I've been trying to retrieve the data using the code snippet provided below: public void fetchDataFromDoc() { String url = "https://spreadsheets ...

Execute asynchronous JavaScript request

When a user types something into the input id=2, an ajax function triggers. Here is the HTML: <input id="2" type="text" onkeyup="posttitulo(this.value)" /> And here is the SCRIPT: function posttitulo(value){ $.post("getdata/posttitulo.php",{p ...

javascript href clears Internet Explorer webpage

I noticed a strange issue with my HTML page. In Internet Explorer, when I click on the link, it displays the return value on a blank page. However, in Chrome, it simply executes the function without affecting the page appearance. Is there a way to make I ...

Utilize the dropdown menu to load JSON data and dynamically update the content of a div section on a website

I have been struggling to find a way to load JSON data from a drop down menu into a div area and refresh it with new results. While I was able to display the data in the div area without the dropdown menu, I am facing difficulty in fetching the required da ...

Is there a way to simulate a click event within a Jasmine unit test specifically for an Angular Directive?

During the implementation of my directive's link function: $document.on('click.sortColumnList', function () { viewToggleController.closeSortColumnList(); scope.$apply(); }); While creating my unit test using Jasmine: describe(&apo ...