0

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

That return statement will cause an error because this.offersData.item is undefined when the component initializes. And this.offersData will always be truthy in that context. I'd do if (this.offersData.item && this.offersData.item[0]) { return this.offersData.item[0].id }
Ah, missed that part out, thank you. I made a shortcut here, as this.offersData.item is undefined initially, and can be only set up by a call returning an array - so if it fails, it fails for a reason.
Thanks, as i understand data () is for static values and v-model, right? Also why do you set this.offersData.item && before id? Still can't get it.
Because initial value of this.offersData is an empty object - and when id() is called the first time, attempt to check the whole path results in error (attempt to access property 0 of undefined). This way, the check is avoided with so-called short-circuit evaluation - id is undefined until filled, no error thrown.
Yes, you can, but as properties, not as methods (i.e., you should write this.id, not this.id())
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.