What are the steps to troubleshoot a Vue application?

I've encountered an issue with a code snippet that retrieves JSON data from a RESTful API. The code only displays the .container element and reports that the items array is empty, even though no errors are being shown. I attempted to debug the problem by using console.log to display the fetch result, so I inserted

let result = await fetch('video').then(res => res.json())
into the code. However, nothing appeared in the browser console, indicating that the async getData function may not be running. I'm puzzled by this behaviour and unsure of what could be causing it.

<template lang="pug">
.container
  .columns(v-for="n in lines")
    .column.is-3.vid(v-for='item in items')
      .panel
        p.is-marginless
         a(:href='item.videoId')
           img(:src='item.thumbnail')
        .panel.vidInfo
          .columns.hax-text-centered
            .column
              .panel-item.reddit-ups
                span {{ item.score }}
                i.fa.fa-reddit-alien.fa-2x
              .panel-item.reddit-date
                i.fa.fa-calendar.fa-2x
</template>
<script>
export default {
      name: 'main',

      data: () => ({
        items: [],
        lines: 0
      }),

      async getVideo () {
        this.items = await fetch('/video').then(res => res.json())    
        this.lines = Math.ceil(this.items.length/4)

      }
  }
  </script>

Answer №1

Your code has a few issues that the console should warn you about.

Start by defining the data object as an ES6 Object Method Shorthand instead of using arrow functions:

data() {
  return {
    items: [],
    lines: 0
  }
}

Next, if 'getVideo' is a method, it should be placed under the methods object:

methods: {
  async getVideo () {
        this.items = await fetch('/video').then(res => res.json())    
        this.lines = Math.ceil(this.items.length/4)
  }
}

I recommend using the created hook to trigger this method, but you can choose when to trigger it (on click, instance creation, or mounting):

<script>
export default {
      name: 'main',

      data() {
        return {
          items: [],
          lines: 0
        }
      },

      methods: {
        async getVideo () {
           await fetch('/video')
              .then(res => res.json())
              .then(items => this.items = items)    
           this.lines = Math.ceil(this.items.length/4)
        }
      },

      created() {
        this.getVideo()
      }
  }
  </script>

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

What steps can I take to ensure that the elements are in the same row instead of being displayed in three separate rows?

(I'm a beginner in web development and need some help) Is there a way to align elements into the same row instead of stacking them up in separate rows? I'm working on creating a header bar similar to the one on the Naive UI Documentation Website. ...

Create a toggle effect using attribute selectors in CSS and JavaScript

I am looking to switch the "fill: #000;" from the CSS property "svg [id^='_']". Usually, I would use a method like this, but it seems that I can't do so because "svg [id^='_']" is not an element, correct? pub.toggleClass = functi ...

Cross domain Ajax POST requests using CodeIgniter and AjaxBy utilizing CodeIgn

Initially, I would like to clarify ... I own two domains: www.one.com and www.two.com The first domain www.one.com has a form input below <div class="hidden cswrap2"> <h3>Edit Data Mustahik</h3> <div class="cscontent"> ...

The replace method for strings in JavaScript does not function properly on mobile devices

I encountered an issue with the string replace method I implemented on my website. Upon checking the page using the web browser on my Android phone, I noticed that it was not functioning as intended. Here's a snippet of the code: /*The function is ...

How can we effectively implement conditional rendering when dealing with components that are nearly identical?

Depending on whether the user is a professor, student, or not logged in, I render different landing pages. The landing pages are quite similar, with the only distinction being the buttons displayed. While I could easily achieve this using inline conditions ...

What is the best way to combine several plugins in tinymce?

I experimented with a basic code snippet to test tinyMCE, and everything is functioning properly. However, I encountered an issue when attempting to add multiple plugins simultaneously. In this instance, I utilized the tinymce CDN for reference. Below is ...

Unable to locate video identifier on ytdl

Lately, I have been working on developing a music bot for Discord. I have successfully managed to make it join and leave voice channels flawlessly, but playing music has proven to be quite challenging. For some reason, the play and playStream functions do ...

Protractor experiencing difficulty in adjusting price slider

As a newcomer to protractor, I am attempting to test a price slider that sorts products based on the provided price range. Unfortunately, I am facing difficulty in dragging the slider (min point) using protractor. Can anyone provide guidance on how to move ...

How can I use JavaScript to sort through an array and organize the data into groups?

Below is an array that I currently have: Status=["active","inactive","pending","active","completed","cancelled","active","completed"] I am looking to achieve the following result: StatusInfo=["active":3,"inactive":2,"pending":1, "completed":2, "cancelle ...

Improving the efficiency of JSON data retrieval in JavaScript

I possess a hefty 10MB JSON file with a structured layout comprising 10k entries: { entry_1: { description: "...", offset: "...", value: "...", fields: { field_1: { offset: "...", description: "...", ...

python extract values from a JSON object

I've been searching everywhere, but I haven't been able to find a solution. It seems like my question is not clear enough, so I'm hoping to receive some guidance. Currently, I am working with turbogears2.2. In my client view, I am sending a ...

Is a Javascript-only application compatible with Amazon S3 cloud storage?

I am currently investigating the validity of the following statement: Based on my research, it seems unlikely to create a web application using only JavaScript - without any server-side logic - hosted on Amazon S3 that can also store data solely on S3 whi ...

Error message: The 'Access-Control-Allow-Origin' policy is preventing access in a react express docker application

I have successfully set up a front-end React application and a Node/Express API using Docker. The React app is currently running on localhost:3000, while the API is running on localhost:9000. Both applications are fully functional. However, I am encounteri ...

Begin by initializing a variable within the `mounted` lifecycle hook and then pass it back to

Experimenting with the new composition api. Check out the composable function useProduct.js below: export default function useProduct() { const product = reactive({}); async function getProduct(id) { try{ const response = await { ...

Implementing a button callback function using Aurelia binding

Is there a way to pass an array of custom button objects to a specific element? Here's an example: <my-component header="My Title" buttons.bind="[{icon: 'fa-plus', display: 'New', action: onNew}]"> </my-component> ...

Error: Trying to access the 'previous' property of an undefined value

I keep encountering an error with functions in firebase: TypeError: Cannot read property 'previous' of undefined at exports.sendNotifications.functions.database.ref.onWrite (/srv/index.js:5:19) at cloudFunction (/srv/node_modules/firebase-functi ...

Modifying the URL does not alter the selected tab

As part of my project, I wanted to ensure that when the page is refreshed, the previously selected tab remains active. To achieve this, I created a basic HTML page and added some jQuery. However, I encountered an issue when manually changing the URL from ...

Tips for transferring date values in an ajax request to a web application handler

I am currently working on plotting a graph between two dates using Google Charts. My goal is to send date values to the controller, which is implemented with webapp2. However, I am facing difficulties in figuring out how to send date values to the controll ...

Incorporating External HTML Content Using JQuery Function

Looking for assistance with a JQuery function: function addSomeHTML() { $("#mysection").html("<div id='myid'>some content here</div>"); } I am trying to have this part: <div id='myid ...

Displaying Props Information in a Modal Window using React

Currently venturing into the realm of React JS, where I am in the process of developing a sample eCommerce application for real-time use. However, I have hit a roadblock. In my Products List, there is a Buy button for each product. When clicking on this b ...