Javascript: Error when loading the page

I'm making an API call, and every time the page loads it comes with this error and I don't know why. Can anyone tell me why? I've tried to put it:

What browser says

Here is the markup where I use the total amount:

<div class="summary__graph">
        <div class="graph__header">
          <h3 class="headline">Fordeling</h3>
          <p class="answers">{{company.amount.total}} besvarelser</p>
        </div>

Here's where I define my company I fill with total value

 data () {
    return {
      selected: 1,
      datacollection: null,
      datacollection2: null,
      datacollection3: null,
      company: '',
      isActive: false,
      scoreLine: null,
      timeBar: null,
      answerPercent: null

    }
  },

vue.js mounted and methods

  mounted () {
    this.getStoreScore()
    this.fillData()
    this.fillData2()
    this.fillData3()
    this.fillDataScoreLine()
    this.fillDataTimeBar()
    this.fillDataAnswerPercent()
  },


getStoreScore () {
      return axios.post('API', {
        storeId: '5b7515ed5d53fa0020557447'
      }).then(response => {
        this.company = {
          'storeScore': response.data.result,
          'amount': {
            'total': response.data.amount.total,
            'zero': {
              'amount': response.data.amount.zero,
              'percentage': response.data.amount.zero / response.data.amount.total * 100
            },
            'one': {
              'amount': response.data.amount.one,
              'percentage': response.data.amount.one / response.data.amount.total * 100
            },
            'two': {
              'amount': response.data.amount.two,
              'percentage': response.data.amount.two / response.data.amount.total * 100
            },
            'three': {
              'amount': response.data.amount.three,
              'percentage': response.data.amount.three / response.data.amount.total * 100
            }
          }
        }
        return this.company
      })
    },

Can anyone tell me why it gives me that error? :D

Upvotes: 1

Views: 1093

Answers (1)

Bertijn Pauwels
Bertijn Pauwels

Reputation: 585

Because you're making an API call, the page gets rendered before you receive any data. You get the error because company.amount is undefined when the page gets rendered. There are a few fixes possible: either you delay your page rendering until all the data is received, or you write a quick if condition around the

<p class="answers">{{company.amount.total}} besvarelser</p>

More info: https://v2.vuejs.org/v2/guide/conditional.html

Edit: Your code would become

<p v-if="company.amount" class="answers">{{company.amount.total}} besvarelser</p>

Upvotes: 3

Related Questions