PenAndPapers
PenAndPapers

Reputation: 2108

Vue JS unable to display to DOM the returned data of method

Template html

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

Method

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'm trying to display the returned data to DOM but it doesnt display anything. But when I try to console log the data is displays. How can I be able to display it. What am I missing?

Upvotes: 3

Views: 1098

Answers (2)

Julian
Julian

Reputation: 1467

You shouldn't use methods for AJAX results because they are async. You could retrieve the full teamRoster object and then add this to your div:

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

Upvotes: 0

Phil
Phil

Reputation: 164812

Problem is, your getFantasyScore method doesn't return anything and even then, the data is asynchronous and not reactive.

I would create a component that loads the data on creation. Something like

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
      })
  }
})

and then in your template

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

Upvotes: 3

Related Questions