Leveraging Vue.js to showcase API information through attribute binding

My application is designed to allow a user to select a Person, and then Vue makes an API call for that user's posts. Each post has its own set of comments sourced from here.

You can view the codepen here

Here is my HTML structure:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id='app'>
<div v-if='isError'>
There was an error
</div>
<div v-else-if='isLoading'>
Loading...
</div>

...

</div>

JavaScript logic implementation:

var app = new Vue({
  el: '#app',
  data: {
    info : null,
    isLoading : true,
    isError : false,
    selectedUser : '',
    postData : null,
    isLoadingPosts : true,
    commentData : null,
  },

 ...

  }
})

Despite everything functioning correctly, I am facing challenges with the comments section as it always seems to be empty. Additionally, I believe there might be some repetitive code in my implementation. Any suggestions or corrections would be highly appreciated. Thank you!

Answer №1

There are a few issues with the current method being used:

getComments : function (){
    axios
        .get('https://jsonplaceholder.typicode.com/posts/' + this.id + '/comments')
      .then(response => (this.commentData =response.data))
    }
  }

The use of this.id in the code snippet will refer to an id property on the component itself, not the actual id that should be bound to the button.

To fix this issue, update your button code to:

<button v-on:click='getComments(post.id)'>View Comments</button>

And adjust the method like so:

  getComments : function (id){
    axios
        .get('https://jsonplaceholder.typicode.com/posts/' + id + '/comments')
      .then(response => (this.commentData =response.data))
    }
  }

Additionally, consider adding a .catch() handler for error handling purposes as you have done with other axios calls.

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 modify the style value within AngularJS?

<div class="meter"> <span style="width: 13%"></span> </div> I have the following HTML code snippet. I am looking to update the width value using AngularJS. Does anyone have a solution for this issue? ...

When trying to pass context to the interactive node shell, an error message may appear stating "TypeError: sandbox argument must be converted to a context"

I am trying to initiate an interactive node shell with pre-initialized objects. But when I use the code below, it gives me an error: var repl = require('repl') var x = 11, y = 21 var con = {} con.x = x con.y = y repl.start('> &apo ...

Encountering [object, Object] while attempting to display JSON object retrieved from req.body in the console

While attempting to insert a product's details into my API's PostgreSQL database using Postman, I encountered an issue where the values of the specs key were displayed as [object Object] instead of showing the complete data. As a result, even in ...

Define JSON as writeable: 'Error not caught'

I'm facing an issue with a read/write error in my JavaScript code because the JSON file seems to be set as read-only ('Uncaught TypeError: Cannot assign to read only property'). How can I change it to writable? Should I make changes in the J ...

Endless [React Native] onFlatList onEndReached callback invoked

Attempting to create my debut app using ReactNative with Expo, I've hit a snag with FlatList. The components are making infinite calls even when I'm not at the end of the view. Another issue might be related; across multiple screens, the infinite ...

How to send a contact form in Wordpress with multiple attachments via email without using any plugins

The main objective is to enable users to submit their own content for new articles (including text and files) to the administrator's email. A form has been created for this purpose: <form class="form form-send" enctype="multipart/fo ...

Learn how to implement a feature in your chat application that allows users to reply to specific messages, similar to Skype or WhatsApp, using

I am currently working on creating a chatbox for both mobile and desktop websites. However, I have encountered an obstacle in implementing a specific message reply feature similar to Skype and WhatsApp. In this feature, the user can click on the reply butt ...

How do you load a map with Vue.js Highmaps?

Recently, I started working with Vue.js and today I am experimenting with setting up a map to display data. After some research, I opted for Highmaps as it seemed like the most suitable option, especially because I have used Highcharts in previous projects ...

Crop box overlaying video background

Utilizing jCrop to establish a crop region for a video element. My goal is to make the video section within the crop area fill a container with identical proportions, but I'm encountering challenges with the mathematical calculations. The sizes of th ...

React Router 4 - Optimizing Component Refresh by Remounting Instead of Re-Rendering

I am currently in the process of configuring a React project that utilizes React Router 4 ("react-router-dom": "^4.3.1"). Within this project, I have implemented a SideBar, a NavBar, and the main content section of the application which changes based on th ...

Issue involving retrieving keys from multiple classes in a JSON object

I am facing some difficulties with JSON and JavaScript as I am a beginner in this area. Currently, I am attempting to iterate through all the keys["name"] of this JSON data. var l = [{ "pages": [ { "name": "Scan", "elements": [ { "type": ...

The HTML5 camera feature remains active even after navigating to a different page in an AngularJS application

I am currently exploring the video capabilities of HTML5. Using a directive userMedia, I have successfully activated my camera on my MacBook through navigator.getUserMedia() (using an adapter for cross-browser compatibility with supported browsers). Howev ...

Sending a PDF document and JSON data via an AJAX POST request

I'm attempting to send a PDF document along with some JSON data in string format using an AJAX method in jQuery to an ASP.NET WEB API (2). Below are my attempts that are not working: JAVASCRIPT: // Obtaining the authorization token works fine var hea ...

Unique trigger for clicking events with customizable widgets in JQuery

I'm in the process of developing a jquery widget that functions similarly to a menu bar, featuring two buttons - ButtonOne and ButtonTwo. With my HTML code and associated styles in place, I've been focusing on creating a "hello world" widget. / ...

Issues encountered when selecting table data for filtering

One issue I am facing is with my HTML table that contains a lot of data. I have created a select option to filter the table and display the filtered data. The select options are based on the "route" column, with only three options available: Marikina, Mont ...

Transform an operational VueJS component into ReactJS

There's a Vue component that functions perfectly. Now, I am attempting to convert the code to its ReactJS equivalent. My progress so far in React: var ticksArray = Array.apply(null, {length: 27}).map(Number.call, Number); export default class Tim ...

Developing a Highchart Graph using JavaScript

I am trying to develop a high chart graph. Check out my code on FIDDLE LINK. I have two values, a and b, for the x-axis and y-axis. The issue arises when the difference between a and b is minimal, such as when both are equal (-9). In such cases, the grap ...

Understanding the visibility scope in JavaScript's object-oriented programming

I have the following code snippet: function A() { this.AFunction = function() { var b = new B(); b.BFunction(); } } function B() { this.BFunction = function() { // some code $.ajax({ url: url suc ...

validating if Object may be either 'null' or 'undefined'

In the code snippet below, I am attempting to verify whether hostel.country.address is null: return hostel.country.address && hostel.country.address.internalEmployeeIdentifier !== null || hostel.country.address.exter ...

What could be causing my function to not successfully retrieve elements based on their text content?

A function called matchTagAndText is designed to take two arguments: a selector and text, checking if any matched elements contain the specified text. The function code is as follows: function matchTagAndText(sel, txt) { var elements = document.queryS ...