L
L
Lord_Dantes2021-06-01 19:26:36
Vue.js
Lord_Dantes, 2021-06-01 19:26:36

How to properly process data through axious?

the code
methods: {
    getProductData() {
      this.axios
        .get('http://church/wp-json/wp/v2/news?slug=' + this.$route.params.slug)
        .then(response => this.currentProductData = response.data);
    },
    getMediaUrls() {
      this.currentProductData[0].acf.photos.forEach(el => {
        this.media.readyURLs.push(el.photo);
      })
    }
    
  },

I call the 1st method with created(), the 2nd with mounted(). Swears at ".acf", I conclude that the data does not have time to be loaded, the question is how to receive data so that there are no errors. Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Aetae, 2021-06-01
@Lord_Dantes

Vue hooks are synchronous. Nobody is waiting for anyone. Do not call getMediaUrlsuntil there is data.
If the call occurs in a template - firstly: do not use methods in templates unless absolutely necessary: getMediaUrls​​there should be computeda property instead of a method mediaUrls; second: hide in the template the display until the data appears: / and show some thread loader instead, Vue will not request what is hidden under until the condition becomes true. ...upd: looked at the full code. There is no need to take out and break the asynchronous chain. Call it immediately in , or if it can change in other cases - make, again, a computed property. In extreme cases, you can call it by hanging onv-if="currentProductData"v-if="currentProductData.length"v-if
getMediaUrlsmountedgetProductDatacurrentProductDatawatchcurrentProductDatabut computedbetter.

V
VegasChickiChicki, 2021-06-01
@VegasChickiChicki

async getProductData() {
      await this.axios
        .get('http://church/wp-json/wp/v2/news?slug=' + this.$route.params.slug)
        .then(response => this.currentProductData = response.data);
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question