0

Ok I'm a beginner at VueJS and I'm just trying to do a simple XHR call and bind the json data response to my variable...

I have a component App.vue and this part of the template I want to show the results of the json. bpi is the name of the variable

<div id="simulationPoints">
    <h2 className="logTitle">Full Log:</h2>
    {{ bpi }}
</div>

then my script

export default {
  name: 'App',
  data: () => ({
    bpi: []
  }),
  mounted: () => {
    axios.get(`https://api.coindesk.com/v1/bpi/historical/close.jsonp?start=2011-01-01&end=2018-02-01`)
      .then(response => {
        this.bpi = response.data.bpi
      })
      .catch(e => {
        this.errors.push(e)
      })
  }
}

This doesn't seem to work. I'm using Axiom to fetch the data and assign the response, and this is how all the examples I found online did it, but the array object I have is still empty and it doesn't render on the page. I don't know whats the issue here? A Vue expert please help :)

Gofishus
  • 79
  • 1
  • 4

1 Answers1

1

There are sorts of problem in your code.

First, don't use arrow function on options property or callback since arrow functions are bound to the parent context, this will not be the Vue instance as you’d expect.

Second, use return statement in your data function.

Third, use created hook for inserting data after instance is created. mounted hook is called for mutation after DOM is rendered.

export default {
  name: 'App',
  data: function() {
    return {
      bpi: []
    }
  },
  created() {
    axios.get(`https://api.coindesk.com/v1/bpi/historical/close.jsonp?start=2011-01-01&end=2018-02-01`)
      .then(response => {
        this.bpi = response.data.bpi
      })
      .catch(e => {
        this.errors.push(e)
      })
  }
}
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231