Alexander Kim
Alexander Kim

Reputation: 18382

Access axios response data in created function - Vue2

Fetching categories from API, saving it's response in data variable categories, then trying to use response data in mounted ():

data () {
  return {
    categories: {}
  }
}

created () {
  this.fetchCategories()
  this.showArticles(this.categories[0].id)
}

methods: {
  fetchCategories () {
    return axios.get(globalConfig.FAQCATS_URL)
      .then((resp) => {
        this.categories = resp.data
      })
      .catch((err) => {
        console.log(err)
      })
    }
}

But getting an error: Cannot read property 'id' of undefined. I guess axios's promise is async, that's why i can't use it's reponse inside created or mounted. How can i access it's response correctly?

Purpose of my actions, is to set default category on a page load, so page won't be empty, because i'm not showing any items, if category is not chosen.

showArticles method:

showArticles (id) {
  return axios.get(globalConfig.FAQCATS_URL + '/' + id + '/articles')
    .then((resp) => {
      this.articles = resp.data
      // console.log(resp)
    })
    .catch((err) => {
      console.log(err)
    })
}

Upvotes: 0

Views: 288

Answers (2)

Hozhabr
Hozhabr

Reputation: 452

Create function created before the mounted and methods, so in the first, you can use mounted instead create second you can call the API in the Created instead methods and then store the response in the store function because of you don't access to data variable before mounted.

data () {
  return {
    categories: {}
  }
}

mounted() {
  this.fetchCategories()
}

methods: {
  fetchCategories () {
    return axios.get(globalConfig.FAQCATS_URL)
      .then((resp) => {
        this.categories = resp.data;
        this.showArticles(this.categories[0].id)
      })
      .catch((err) => {
        console.log(err)
      })
    }
    }

Upvotes: 0

t.niese
t.niese

Reputation: 40842

You will have to wait for the Promise returned by fetchCategories to resolve using .then:

this.fetchCategories()
    .then(() => this.showArticles(this.categories[0].id))

Or if you can use await/async:

async created () {
  await this.fetchCategories()
  this.showArticles(this.categories[0].id)
}

But you probably want to use watch:

data () {
  return {
    categories: null
  }
}

watch: {
  categories( newList, oldList ) {
     if( !oldList ) {
        // only call showArticles if categories was not et before
        this.showArticles(this.categories[0].id)
     }
  }
} 

created () {
  this.fetchCategories()
}

Upvotes: 1

Related Questions