Alexander Kim
Alexander Kim

Reputation: 18411

How to use axios response data in data function - vue

Using axios to fetch api data:

fetchData () {
  axios.get(globalConfig.OFFERS_URL)
    .then((resp) => {
      this.offersData = resp.data
      console.log(resp)
    })
    .catch((err) => {
      console.log(err)
    })
}

Data function:

  data () {
    return {
      offersData: {}
    }
  }

Now i can use fetched data in my template, like so: {{ offersData.item[0].id }}

But can i set the fetched data in a data function:

  data () {
    return {
      offersData: {},
      id: this.offersData.item[0].id
    }
  }

It's not working for me, is that even possible to store axios get's response in a data function?

Upvotes: 0

Views: 1077

Answers (1)

raina77ow
raina77ow

Reputation: 106463

You probably are looking for computed property:

data () {
  return {
    offersData: {},
  }
},
computed() {
  id() {
    return this.offersData.item && this.offersData.item[0].id;
  }
}

As for data function, it is used to define shape of state (set up the properties to be tracked) of component and give valid initial values to it. In this case, however, id should neither be a part of state (it's always a part of offersData value, after all) nor its initial value can be calculated before offersData is set up by a remote call.

Upvotes: 3

Related Questions