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

Cancel promise chain after action dispatch (rxjs)

My goal is to achieve the following: this.jobManager .queue( // initiate a job ) .then( // perform additional actions, but stop if `ABORT` action is dispatched before completion ) .finally( // carry out necessary ...

What is the method for adding a prefix to every line in JavaScript?

I'm currently working on a React project and dealing with a string that may contain newlines. I'm looking for the most efficient way to inject a symbol at the start of each line. I've considered exploding the string into an array and adding ...

Encountering an incorrect number of parameters for "undefined" during the deployment of a smart contract

I am facing an issue while attempting to deploy my first Voting contract on the testRPC. The error seems to arise from the arguments parameter in the code snippet below. When I tried passing an empty array, it gave an error stating "Got 0 expected 1!". Si ...

Retrieve the values by accessing an element upon clicking the "Submit" button

Here is an interesting example that I found on this website I am currently working on a simple webpage to display both the current forecast and extended forecast. This is my Index.html: <!DOCTYPE html> <!-- To change this license header, choose ...

Utilizing JSON Data with Angular

Currently, I am in the process of developing an AngularJS client that communicates with a REST API running on NodeJS. To retrieve data, I make GET requests by accessing specific URLs with stock symbols appended, such as localhost:8080/stocks/aapl for Apple ...

Tips for effectively passing an array to props in Vue when leveraging Typescript and the class component decorator

I'm currently struggling to understand the proper method of passing an array as a prop to a component in Vue, using Typescript and the class component library. Following the official template, I attempted the following approach: <script lang="ts"& ...

Navigating using inertia.js and jetstream in JavaScript implementation

Upon creating a question, I wish to be automatically directed to the single question page. summitQuestion(){ this.question_button = true axios.post('/api/question/ask', { 'title' : this.question.title, 'body ...

Tips for disabling drag slide functionality in Vue with agility

I am working with vue-agile and encountering an issue where videos are causing the slider to move unexpectedly when dragging the player's pointer. Images display fine, but this drag/swipe behavior is disrupting the user experience. Is there a way to d ...

Tips for restricting User access and displaying specific sections of the menu

I have a component that utilizes map to display all menu parts. Is there a way to make certain parts of the menu hidden if the user's access rights are equal to 0? const Aside: React.FunctionComponent = () => { const[hasRight, setHasRight] = us ...

Deactivate while maintaining menu options

Currently, I have a Vue.js form that manages adding and updating data for patients. The issue at hand involves a <select> tag which allows for the addition of a relative. This select field is populated by an array called PPrelations, which is sourced ...

Retrieving the selected date from mat-datepicker into a FormControl

When creating a POST request to an API, I encountered an issue with the mat-datepicker field as it throws an error when inside the ngOnInit() call (since nothing is selected yet). Other fields like name, email, etc. work fine, but extracting a value from t ...

Using ajax for sending data is a breeze, but I am encountering trouble when attempting to receive data back from

I have a function that retrieves a value from an input and sends data through ajax to another PHP file. However, I am facing an issue where I cannot retrieve the result back from the PHP file even though I echo it in the ajax success function. <script&g ...

Navigational elements, drawers, and flexible designs in Material-UI

I'm working on implementing a rechart in a component, but I've encountered an issue related to a flex tag. This is causing some problems as I don't have enough knowledge about CSS to find a workaround. In my nav style, I have display: flex, ...

detect mouse click coordinates within an iframe that spans multiple domains

I am currently encountering an issue with tracking click position over a cross-domain iframe. Here is my current code: <div class="poin"> <iframe width="640" height="360" src="http://cross_domain" frameborder="0" allowfullscreen id="video">< ...

Paper.js: Is there a way to prevent canvas height and width from changing when the window is resized?

My canvas with paperjs is set up to resize dynamically when the window is resized. I appreciate any help in advance. HTML <canvas id="myCanvas" height="800" width="1000"></canvas> JS var Initialize = function () { var canvas = document ...

The hierarchy of CSS in Vue components

I've developed a customized CSS framework to streamline the design process across all my internal projects. The central file is structured as shown below: @import "~normalize.css/normalize.css"; @import "_variables.scss"; @import "_mixins.scss" ...

``A bidirectional data exchange mechanism enabling seamless communication between a parent and child

Currently, I am in the process of learning VueJS and experimenting with building a basic application that involves listing, viewing, creating, editing, and deleting stories. Each story consists of a title, content (text only), and a datetime stamp. So far, ...

Incorrect data retrieval from JSON object with JQUERY

I am working on a function that extracts data from a database on the server-side and assigns it as the value of a textbox on the client-side. The function is functioning correctly on the server-side, but on the client-side, when I use console.log to view t ...

I am currently studying JavaScript. The syntax of my if statement with && appears to be accurate, however

I'm having trouble with the logic in my "Code your Own Adventure" program on Code Academy. I expect it to display "Great, come get your pizza!" when I enter PIZZA, YES, and YES as prompts, but instead it says "NO pizza for you!" I've tried using ...

The transformation of a Raphael element does not occur as expected when it is passed to a function within a loop

My attempt to rotate an object by a variable number of degrees in order to mimic a dial was unsuccessful. Initially, I tried the following steps: window.onload = function() { var paper = new Raphael(document.getElementById('canvas_container ...