Vue JS encountering issues in rendering method's returned data on DOM

HTML Template

<div class="item" v-for="n, index in teamRoster">
   <span> {{ getFantasyScore(n.personId) }} </span>
</div>

Function

getFantasyScore(playerId) {
    if(playerId) {
        axios.get(config.NBLAPI + config.API.PLAYERFANTASYSCORE + playerId)
        .then( (response) => {
            if( response.status == 200 ) {
                console.log(response.data.total)
                return response.data.total;
            }
        });
    }
}

I am facing an issue where the data returned is not being displayed on the DOM. However, when I try to log it in the console, it shows up. What could be causing this and how can I rectify it?

Answer №1

It seems like the issue lies in your getFantasyScore method as it does not have a return value and the data is asynchronous rather than reactive.

To address this, I would suggest creating a new component that fetches the data upon creation. Here's an example:

Vue.component('fantasy-score', {
  template: '<span>{{score}}</span>',
  props: ['playerId'],
  data () {
    return { score: null }
  },
  created () {
    axios.get(config.NBLAPI + config.API.PLAYERFANTASYSCORE + this.playerId)
      .then(response => {
        this.score = response.data.total
      })
  }
})

Once you have defined the component, you can use it in your template like this:

<div class="item" v-for="n, index in teamRoster">
  <fantasy-score :player-id="n.personId"></fantasy-score>
</div>

Answer №2

Avoid using AJAX methods to handle asynchronous results. It is recommended to first fetch the complete teamRoster object and then insert it into your div:

<div class="item" v-for="fantasyScore in teamRoster" v-if="teamRoster">
   <span> {{ fantasyScore }} </span>
</div>

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

The correct method for including a CSS file in a Vue.js application

How can external CSS files be properly added in a Vue.js Application? I have come across multiple methods for adding CSS files in a Vue.js Application. One suggestion is to use the following code: <link rel="stylesheet" type="text/css" href="/static/b ...

tips for incorporating jade Mixin in JavaScript

Experimenting with test mixins in jade language mixin test(testName) #test span Test String Desire to incorporate this functionality into javascript (as declared in the jade file) script(type='text/javascript'). $( document ).on( "cli ...

Adding express.js to a Pre-existing vue.js/webpack Setup

Can express.js be added to an existing vue.js/webpack project that currently only uses node.js without a framework? If the vue.js project is created at the root folder level, can a sub-folder be added at the root level for the express.js files? Will this ...

Unpacking Reddit's JSON data in a Node environment proves challenging as the Javascript parser seems to have a distaste for

Hey there, I hope everything is going well! I've been working on a project that involves scanning the JSON data from reddit.com/r/pics. My goal is to extract a random image and display it on a webpage. The issue I'm facing is that Reddit's ...

What is the best way to display text from one text field onto another text field?

Here's a challenging question that I've been pondering... Issue: I am using a virtual keyboard that needs to interact with different text fields on various pages. Every time I click on a text field, the keyboard should appear, and every key I pr ...

Is it possible to automate the firing of setTimeout events using WebDriver?

Looking to test pages with numerous setTimeout functions, I'm searching for a way to expedite the code execution upon page load rather than waiting for it to run on its own. One idea is to inject custom JavaScript like this into the page before evalu ...

Retrieving search results in JSON format from a website with NodeJs

I recently started learning Node and attempted to retrieve a website's search result in JSON format using Node. I experimented with the HTTP chunk method and Express GET, but unfortunately, was unable to find a solution. The specific URL I was working ...

Combine two objects while keeping only specific properties

Currently facing a challenge with merging two objects in the desired way using Node.js express and MongoDB. Here are the initial objects: Obj1: { "name":"max", "age":26, "hometown": & ...

The Firebase cloud function will only activate when I manually input data into the Firestore database via the console

I'm having trouble getting my function to trigger when I programmatically add data to Firestore. It only seems to work when I manually add data through the console. Below is the code for my function: exports.updateFirestoreStatistics = functions.fir ...

You must provide a secret or key in order to use the JwtStrategy

I have encountered the following error and I am unsure of its cause. Can you assist me? ERROR [ExceptionHandler] JwtStrategy requires a secret or key TypeError: JwtStrategy requires a secret or key at new JwtStrategy (C:\Users\wapg2\OneDriv ...

Utilizing JavaScript to retrieve data from a self-submitting form

From my database, I am able to create a list of options for users to choose from. Once a selection is made, the values are submitted back to the same page and retrieved using Javascript. Within the same form, there are radio buttons and a multiple selecti ...

Using Firebase with Vue.js

I'm currently working on developing a straightforward read/write application using Vue.js, VueFire, and Firebase. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>App</title> <!-- Vue --> ...

Retrieve the attribute value from an HTML element in a JSON response using JavaScript

I received a JSON request result containing a blogger post. // API callback posts( { "version": "1.0", "encoding": "UTF-8", "entry": { "title": { "type": "text", "$t": "Vimeo Embed Video Post" ...

Troubleshooting UV Mapping Problem in THREEJS JSON Model

After reviewing the json file for a 3D model, I came across the following line: "uvs": [[-3.21834,-1.65399,-3.21834,-2.57657,4.21834,-2.57657,4.21834,-1.65399,4.21834,-1.85233,4.21834,-2.7749,-3.21834,-2.7749,-3.21834,-1.85233,4.21834,0.961286,-3.21834,0 ...

How can I dynamically display Material-UI's <MenuItem/> within a <DropDownMenu/> using ReactJS?

In my ReactJS + Material-UI project, I am working with an array named colors that contains different color strings such as "white", "blue", and "green. My goal is to render each color string as a <MenuItem/> within a <DropDownMenu/> component ( ...

Having trouble getting the equirectangular panorama example from Three.js to work on your device even though WebGL is supported?

After examining the WebGL equirectangular panorama example, it performs well on both desktop and mobile devices (such as the Samsung S4 Android 4.4.2) using the latest version of mobile Chrome. However, when tested on the Samsung tablet SM-T230 also runni ...

The function fs.createReadStream does not exist

Snippet to Submit Career Form: import axios from 'axios'; import FormData from 'form-data'; var fs = require('fs'); submitCareerForm(e){ e.preventDefault(); let formData = new FormData(); //formdata obje ...

Tips for extracting a specific attribute from an array of objects using both react and JavaScript while considering various conditions

I have a set of objects structured like this: const obj_arr = [ { id: '1', jobs: [ { completed: false, id: '11', run: { id: '6&apos ...

When working with an Angular application, IE9 may display the error message: "An internal error occurred in the Microsoft Internet extensions"

My application is encountering an issue in IE9: Error: A Microsoft Internet Extensions internal error has occurred. Error: Access is denied. When using IE's dev tools for debugging, the issue seems to be related to localStorage. if (localStorage) ...

Should I include all components in the app.js file or import them directly into the Vue component?

Now I am faced with two options for injecting my component into my application. The first method is in app.js Vue.component( "notice-master-component", require("./components/site/communication/Notice/MasterComponent.vue") ); In any Vue ...